MIDAS VWAP Jayy his is just a bash together of two MIDAS VWAP scripts particularly AkifTokuz and drshoe.
I added the ability to show more MIDAS curves from the same script.
The algorithm primarily uses the "n" number but the date can be used for the 8th VWAP
I have not converted the script to version 3.
To find bar number go into "Chart Properties" select " "background" then select Indicator Titles and "Indicator values". When you place your cursor over a bar the first number you see adjacent to the script title is the bar number. Put that in the dialogue box midline is MIDAS VWAP . The resistance is a MIDAS VWAP using bar highs. The resistance is MIDAS VWAP using bar lows.
In most case using N will suffice. However, if you are flipping around charts inputting a specific date can be handy. In this way, you can compare the same point in time across multiple instruments eg first trading day of the year or an election date.
Adding dates into the dialogue box is a bit cumbersome so in this version, it is enabled for only one curve. I have called it VWAP and it follows the typical VWAP algorithm. (Does that make a difference? Read below re my opinion on the Difference between MIDAS VWAP and VWAP ).
I have added the ability to start from the bottom or top of the initiating bar.
In theory in a probable uptrend pick a low of a bar for a low pivot and start the MIDAS VWAP there using the support.
For a downtrend use the high pivot bar and select resistance. The way to see is to play with these values.
Difference between MIDAS VWAP and the regular VWAP
MIDAS itself as described by Levine uses a time anchored On-Balance Volume (OBV) plotted on a graph where the horizontal (abscissa) arm of the graph is cumulative volume not time. He called his VWAP curves Support/Resistance VWAP or S/R curves. These S/R curves are often referred to as "MIDAS curves".
These are the main components of the MIDAS chart. A third algorithm called the Top-Bottom Finder was also described. (Separate script).
Additional tools have been described in "MIDAS_Technical_Analysis"
Midas Technical Analysis: A VWAP Approach to Trading and Investing in Today’s Markets by Andrew Coles, David G. Hawkins
Copyright © 2011 by Andrew Coles and David G. Hawkins.
Denoting the different way in which Levine approached the calculation.
The difference between "MIDAS" VWAP and VWAP is, in my opinion, much ado about nothing. The algorithms generate identical curves albeit the MIDAS algorithm launches the curve one bar later than the VWAP algorithm which can be a pain in the neck. All of the algorithms that I looked at on Tradingview step back one bar in time to initiate the MIDAS curve. As such the plotted curves are identical to traditional VWAP assuming the initiation is from the candle/bar midpoint.
How did Levine intend the curves to be drawn?
On a reversal, he suggested the initiation of the Support and Resistance VVWAP (S/R curve) to be started after a reversal.
It is clear in his examples this happens occasionally but in many cases he initiates the so-called MIDAS S/R VWAP right at the reversal point. In any case, the algorithm is problematic if you wish to start a curve on the first bar of an IPO .
You will get nothing. That is a pain. Also in Levine's writings, he describes simply clicking on the point where a
S/R VWAP is to be drawn from. As such, the generally accepted method of initiating the curve at N-1 is a practical and sensible method. The only issue is that you cannot draw the curve from the first bar on any security, as mentioned without resorting to the typical VWAP algorithm. There is another difference. VWAP is launched from the middle of the bar (as per AlphaTrends), You can also launch from the top of the bar or the bottom (or anywhere for that matter). The calculation proceeds using the top or bottom for each new bar.
The potential applications are discussed in the MIDAS Technical Analysis book.
Cari dalam skrip untuk "the script"
MMTools - Screener❖ Overview
Screener expands your market insights and provides an efficient way to monitor real-time signals from Catcher across hundreds of charts on a single screen.
Each cell in the table displays the number of indicator signals. For instance, a value of "1" in the row labeled ‘BTCUSDT.P’ and column ‘30’ indicates one long signal on the 30-minute Bitcoin chart within the selected lookback period. “0” means no signal in the lookback.
❖ Multi-Table Construction
Screener supports flexible layouts and overlays. To build a multi-table interface, simply add multiple instances of the script to your chart. For optimal usability, it is recommended to allocate a dedicated panel or tab.
⚙️ Key Parameters to Customize Initially
Indicator Lookback: Defines how far back Screener checks for signals.
Symbols: Choose up to 20 symbols. Use additional tables to expand coverage.
Size: Adjusts the overall dimensions of the table.
Display Settings: Customize colors, opacity, and symbol visibility. For dark theme charts, set color opacity to 100% and transparency to 0%.
⚙️ Per-Table Adjustable Parameters
Timeframe: This defines the interval for signal collection across all symbols displayed in the top row of the table. It must be equal to or greater than the chart’s timeframe, otherwise the script will deliberately trigger an error. For multiple tables, use a lower chart timeframe (e.g., 1 minute) to meet this requirement.
Table Positioning: Use either the “Position” (predefined screen locations) or “Block” (stacked layout) parameters. The “Block” method enables a greater number of tables by aligning them side-by-side efficiently.
-- Multi-table example demonstrating the use of the ’Position’ parameter --
-- Multi-table example demonstrating the use of the ’Block’ parameter --
❖ Access
Please refer to the Author's Instructions field to request access to the script.
-----------------------------------------------------------
Disclaimer
The information provided by my scripts is for informational purposes only and does not constitute financial advice. Past performance is not indicative of future results. Always do your own research before making financial decisions.
weighted support or resistance linesQ: Why should users choose this script?
A: I found that in all the publicly available scripts about support and resistance lines, there is basically no weight identification for these lines. In other words, users do not know which support or resistance lines are the most important. So I specifically wrote this script.
1. By adjusting the weights, only the most effective support or resistance lines are displayed. (Length threshold of trend price (Bar))
2. By selecting the number of K-lines, only the latest number of support or resistance lines generated will be displayed. (Maximum number of reserved S/R lines)
3. By selecting whether to automatically remove lines, only support or resistance lines that have not been penetrated by the k-line will be displayed. If this function is checked, the weight can be adjusted lower, as high-weight SR may have already been penetrated, and the newly generated SR may have a lower weight. (Automatically remove lines penetrated by closing price confirmation)
4. Notes: The default parameters work well in 15-minute candlestick charts. For candlestick charts with other time periods, the parameters can be adjusted appropriately. It is suitable for sideways trading but not for strong trends.
5. I'm quite satisfied with the performance of the script, as I specifically optimized it, lol
Integrated Market Analysis IndicatorThe Integrated Market Analysis Indicator is designed to provide traders with a macro perspective on market conditions, focusing on the S&P 500 (SPX) and market volatility (VIX), to assist in swing trading decisions. This script integrates various technical indicators and market health metrics to generate scores that help in assessing the overall market trend, potential breakout opportunities, and mean reversion scenarios. It is tailored for traders who wish to align their individual stock or index trades with broader market movements.
Functionality:
Trend Analysis: The script analyzes the trend of the S&P 500 using moving averages (5-day SMA, 10-day EMA, 20-day EMA) to determine whether the market is in an uptrend, downtrend, or neutral state. This provides a foundation for understanding the general market direction.
Volatility Assessment: It uses the VIX to gauge market volatility, which is crucial for risk management. The script calculates thresholds based on the 20-day SMA of the VIX to categorize the market volatility into low, medium, or high.
Market Breadth: The advance/decline ratio (A/D ratio) from the USI:ADVQ and USI:DECLQ indices gives an indication of market participation, helping to understand if the market movement is broad-based or led by a few stocks.
Scoring System: Three scores are calculated:
Trend Score: Evaluates the market trend in conjunction with volume, market breadth, and VIX to assign a grade from 'A' to 'D'.
Breakout Score: Assesses potential breakout conditions by looking at price action relative to dynamic support/resistance levels, short-term momentum, and volume.
Mean Reversion Score: Identifies conditions where mean reversion might occur, based on price movement, volume, and high VIX levels, indicating potential overbought or oversold conditions.
Risk Management: Position sizing recommendations are provided based on VIX levels and the calculated scores, aiming to adjust exposure according to market conditions.
How to Use the Script:
Application: Apply this indicator on any stock or index chart in TradingView. Since it uses data from SPX and VIX, the scores will reflect the macro environment regardless of the underlying chart.
Interpreting Scores:
Trend Score: Use this to gauge the overall market direction. An 'A' score might suggest a strong uptrend, making it a good time for bullish trades, while a 'D' could indicate a bearish environment.
Breakout Score: Look for 'A' scores when considering trades that aim to capitalize on breakouts. A 'B' might suggest a less certain breakout, requiring more caution.
Mean Reversion Score: A 'B' or 'A' here might be a signal to look for trades where you expect the price to revert to the mean after an extreme move.
Risk Management: Use the suggested position sizes ('Normal Size', '1/3 Size', '1/4 Size', '1/10 Size') to manage your risk exposure. Higher VIX levels or lower scores suggest reducing position sizes to mitigate risk.
Visual Cues: The script plots various SMAs, EMAs, and dynamic support/resistance levels, providing visual indicators of where the market might find support or resistance, aiding in entry and exit decisions.
How NOT to Use the Script:
Not for Intraday Trading: This indicator is designed for swing trading, focusing on daily or longer timeframes. Using it for intraday trading might not provide the intended insights due to its macro focus.
Avoid Over-reliance: While the script provides valuable insights, do not rely solely on it for trading decisions. Always consider additional analysis, news, and fundamental data.
Do Not Ignore Individual Stock Analysis: Although the script gives a macro view, individual stock analysis is crucial. The macro conditions might suggest a trend, but stock-specific factors could contradict this.
Not for High-Frequency Trading: The script's logic and the data it uses are not optimized for high-frequency trading strategies where microsecond decisions are made.
Misinterpretation of Scores: Do not misinterpret the scores as absolute signals. They are guidelines that should be part of a broader trading strategy.
Logic Explanation:
Moving Averages: The script uses different types of moving averages to smooth out price data, providing a clearer view of the trend over short to medium-term periods.
ATR for Volatility: The Average True Range (ATR) is used to calculate dynamic support and resistance levels, giving a sense of how much price movement can be expected, which helps in setting realistic expectations for price action.
VIX for Risk: By comparing current VIX levels to its 20-day SMA, the script assesses market fear or complacency, adjusting risk exposure accordingly.
Market Breadth: The A/D ratio helps to understand if the market movement is supported by a broad base of stocks or if it's narrow, which can influence the reliability of the trend.
This indicator should be used as part of a comprehensive trading strategy, providing a macro overlay to your trading decisions, ensuring you're not fighting against the broader market trends or volatility conditions. Remember, while it can guide your trading, always integrate it with other forms of analysis for a well-rounded approach.
Custom Dual EMA Crossover Strategy with Configurable LogicThis strategy is designed to assist traders in identifying and capitalizing on bullish market trends through a systematic and data-driven approach. It incorporates detailed trend analysis, volatility filtering, and percentage-based thresholds to provide actionable insights and high-confidence trade setups. It leverages the Exponential Moving Average and combines it with custom logic to detect volatility, maximum allowed price movements over last bars and trend confirmation.
Key Features:
- Buy orders follow several conditions, including but not limited to:
a. EMA Crossover: specifically designed to capture immediate market shifts rather than medium- or long-term trends, ensuring responsiveness to rapidly changing conditions but requiring additional confirmations to avoid false signals (see below).
b. Thresholds in Price Changes: Ensures recent price fluctuations remain within specific thresholds, allowing trades to be entered at optimal times and avoiding delayed or unsustainable short-term bullish trends.
c. Adequate Market Volatility: Requires sufficient market activity to avoid false signals stemming from low volatility conditions.
d. Bullish Medium-Term Trend: Validates a bullish medium-term trend using an EMA crossover to avoid trading during bearish market conditions and minimize risk.
- Leverages Take profit and Stop loss levels
- Implements an optional mechanism to automatically close trades after a predefined number of bars, supporting disciplined trade management.
The script does not rely on any public scripts or indicators. Apart the EMA, all the underlying logic, including the volatility thresholds and filtering mechanisms, has been custom developed to ensure originality and precision. The strategy's conditions are all configurable by the user in the TradingView pop-up, allowing it to adapt to different assets and timeframes. For example, users can set the EMA lengths to align with long-term trends for cryptocurrencies or adjust volatility thresholds to account for the specific price movement behavior of stocks or forex pairs.
---
Recommendations:
- Identify a crypto asset with potential
- Before live trading, rigorously backtest your strategy on the chosen asset and interval over a period of at least one year*, analyzing results, refining parameters' value and eventually changing timeframe and / or asset.
- Refine your approach until you achieve consistent profitability with a high win rate. Balance the two — a high win rate is great, but only if your profits outweigh your losses in the long term.
- Once successful, remain disciplined and adhere to the parameters that yield the best results. Set up TradingView alerts to trigger real-time actions via your preferred trading bot. Alerts can be set up on the Indicator, which mirrors the strategy's logic and enables users to execute real-time actions effectively. I will provide you access to the Indicator, as well as the Strategy.
* Alternatively, you can apply the strategy to a shorter period for tactical use. While this approach may increase short-term opportunities (e.g. strong bullish short term movements), it also comes with heightened risks.
Use Cases:
- Suitable for traders focusing on bullish or range-bound markets.
- Ideal for short to medium-term trading horizons.
Access and Configuration Support:
This is an invite-only script. For access, please reach out directly for subscription details. I also provide guidance on configuring the strategy with real-world examples to optimize its use for various assets, intervals and timeframes.
---
Disclaimer:
This script is a tool to support trading decisions and does not guarantee profitability. Past performance does not indicate future results. Trading carries inherent risks; always trade responsibly and manage risk accordingly.
Forex Heatmap█ OVERVIEW
This indicator creates a dynamic grid display of currency pair cross rates (exchange rates) and percentage changes, emulating the Cross Rates and Heat Map widgets available on our Forex page. It provides a view of realtime exchange rates for all possible pairs derived from a user-specified list of currencies, allowing users to monitor the relative performance of several currencies directly on a TradingView chart.
█ CONCEPTS
Foreign exchange
The Foreign Exchange (Forex/FX) market is the largest, most liquid financial market globally, with an average daily trading volume of over 5 trillion USD. Open 24 hours a day, five days a week, it operates through a decentralized network of financial hubs in various major cities worldwide. In this market, participants trade currencies in pairs , where the listed price of a currency pair represents the exchange rate from a given base currency to a specific quote currency . For example, the "EURUSD" pair's price represents the amount of USD (quote currency) that equals one unit of EUR (base currency). Globally, the most traded currencies include the U.S. dollar (USD), Euro (EUR), Japanese yen (JPY), British pound (GBP), and Australian dollar (AUD), with USD involved in over 87% of all trades.
Understanding the Forex market is essential for traders and investors, even those who do not trade currency pairs directly, because exchange rates profoundly affect global markets. For instance, fluctuations in the value of USD can impact the demand for U.S. exports or the earnings of companies that handle multinational transactions, either of which can affect the prices of stocks, indices, and commodities. Additionally, since many factors influence exchange rates, including economic policies and interest rate changes, analyzing the exchange rates across currencies can provide insight into global economic health.
█ FEATURES
Requesting a list of currencies
This indicator requests data for every valid currency pair combination from the list of currencies defined by the "Currency list" input in the "Settings/Inputs" tab. The list can contain up to six unique currency codes separated by commas, resulting in a maximum of 30 requested currency pairs.
For example, if the specified "Currency list" input is "CAD, USD, EUR", the indicator requests and displays relevant data for six currency pair combinations: "CADUSD", "USDCAD", "CADEUR", "EURCAD", "USDEUR", "EURUSD". See the "Grid display" section below to understand how the script organizes the requested information.
Each item in the comma-separated list must represent a valid currency code. If the "Currency list" input contains an invalid currency code, the corresponding cells for that currency in the "Cross rates" or "Heat map" grid show "NaN" values. If the list contains empty items, e.g., "CAD, ,EUR, ", the indicator ignores them in its data requests and calculations.
NOTE: Some uncommon currency pair combinations might not have data feeds available. If no available symbols provide the exchange rates between two specified currencies, the corresponding table cells show "NaN" results.
Realtime data
The indicator retrieves realtime market prices, daily price changes, and minimum tick sizes for all the currency pairs derived from the "Currency list" input. It updates the retrieved information shown in its grid display after new ticks become available to reflect the latest known values.
NOTE: Pine scripts execute on realtime bars only when new ticks are available in the chart's data feed. If no new updates are available from the chart's realtime feed, it may cause a delay in the data the indicator receives.
Grid display
This indicator displays the requested data for each currency pair in a table with cells organized as a grid. Each row name corresponds to a pair's base currency , and each column name corresponds to a quote currency . The cell at the intersection of a specific row and column shows the value requested from the corresponding currency pair.
For example, the cell at the intersection of a "EUR" row and "USD" column shows the data retrieved for the "EURUSD" currency pair, and the cell at the "USD" row and "EUR" column shows data for the inverse pair ("USDEUR").
Note that the main diagonal cells in the table, where rows and columns with the same names intersect, are blank. The exchange rate from one currency to itself is always 1, and no Forex symbols such as "EUREUR" exist.
The dropdown input at the top of the "Settings/Inputs" tab determines the type of information displayed in the table. Two options are available: "Cross rates" and "Heat map" . Both modes color their cells for light and dark themes separately based on the inputs in the "Colors" section.
Cross rates
When a user selects the "Cross rates" display mode, the table's cells show the latest available exchange rate for each currency pair, emulating the behavior of the Cross Rates widget. Each cell's value represents the amount of the quote currency (column name) that equals one unit of the base currency (row name). This display allows users to compare cross rates across currency pairs, and their inverses.
The background color of each cell changes based on the most recent update to the exchange rate, allowing users to monitor the direction of short-term fluctuations as they occur. By default, the background turns green (positive cell color) when the cross rate increases from the last recorded update and red (negative cell color) when the rate decreases. The cell's color reverts to the chart's background color after no new updates are available for 200 milliseconds.
Heat map
When a user selects the "Heat map" display mode, the table's cells show the latest daily percentage change of each currency pair, emulating the behavior of the Heat Map widget.
In this mode, the background color of each cell depends on the corresponding currency pair's daily performance. Heat maps typically use colors that vary in intensity based on the calculated values. This indicator uses the following color coding by default:
• Green (Positive cell color): Percentage change > +0.1%
• No color: Percentage change between 0.0% and +0.1%
• Bright red (Negative cell color): Percentage change < -0.1%
• Lighter/darker red (Minor negative cell color): Percentage change between 0.0% and -0.1%
█ FOR Pine Script™ CODERS
• This script utilizes dynamic requests to iteratively fetch information from multiple contexts using a single request.security() instance in the code. Previously, `request.*()` functions were not allowed within the local scopes of loops or conditional structures, and most `request.*()` function parameters, excluding `expression`, required arguments of a simple or weaker qualified type. The new `dynamic_requests` parameter in script declaration statements enables more flexibility in how scripts can use `request.*()` calls. When its value is `true`, all `request.*()` functions can accept series arguments for the parameters that define their requested contexts, and `request.*()` functions can execute within local scopes. See the Dynamic requests section of the Pine Script™ User Manual to learn more.
• Scripts can execute up to 40 unique `request.*()` function calls. A `request.*()` call is unique only if the script does not already call the same function with the same arguments. See this section of the User Manual's Limitations page for more information.
• Typically, when requesting higher-timeframe data with request.security() using barmerge.lookahead_on as the `lookahead` argument, the `expression` argument should use the history-referencing operator to offset the series, preventing lookahead bias on historical bars. However, the request.security() call in this script uses barmerge.lookahead_on without offsetting the `expression` because the script only displays results for the latest historical bar and all realtime bars, where there is no future information to leak into the past. Instead, using this call on those bars ensures each request fetches the most recent data available from each context.
• The request.security() instance in this script includes a `calc_bars_count` argument to specify that each request retrieves only a minimal number of bars from the end of each symbol's historical data feed. The script does not need to request all the historical data for each symbol because it only shows results on the last chart bar that do not depend on the entire time series. In this case, reducing the retrieved bars in each request helps minimize resource usage without impacting the calculated results.
Look first. Then leap.
Liquidity_Detection_Fx_Shepherd [ALLDYN]### Breakdown of the Basic "Fx_Shepherd_Liquidity" Script
#### 1. **Purpose of the Script:**
This basic version of the "Fx_Shepherd_Liquidity" script is designed to help traders detect potential liquidity grabs by analyzing price movements and candle patterns in the market. It works by identifying large price deviations and compares multiple candles to detect liquidity sweeps either to the upside or downside.
#### 2. **How it Works:**
- **User Inputs:**
- `Maru_rate`: This is a user-defined percentage that helps determine how much the price movement of a candle needs to deviate from the candle's range (high - low) to be considered a liquidity grab.
- `Compare`: Another percentage input used to compare the relative size of three candles versus one candle.
- `MA`: This represents the "Big candle period," or the moving average period for big candles.
- `urgent_rate`: This is used to determine urgency by comparing the current candle's range to an SMA of previous candles.
- **Key Calculation Steps:**
- **Candle Deviation (Up and Down):**
- `Up` measures how much the current candle closes above its open (bullish deviation).
- `Down` measures how much the current candle closes below its open (bearish deviation).
- **Average Deviations:**
- `UP_Sum` and `Do_Sum` calculate the SMA of Up and Down deviations, respectively, over the defined period (MA). These averages help detect when a candle deviates significantly from the norm.
- **Urgency Detection:**
- `Check_Up_Urgent` and `Check_Dow_Urgent` are conditions that check if the current candle’s high-low range exceeds the defined urgent rate. This signals whether the price movement is "urgent" or significant.
- **Liquidity Detection:**
- **For Upward Liquidity:**
- The script checks if the candle is bullish (`close > open`) and whether the price deviation (`close - open`) meets or exceeds the user-defined `Maru_rate`.
- The script then compares the size of the previous three candles (`high - low`) with a single candle (`Compare`) to confirm a liquidity grab.
- Finally, it looks for continuous upward candle patterns to confirm the strength of the move.
- **For Downward Liquidity:**
- Similar logic applies, but for bearish candles. It checks whether the candle is bearish (`close < open`) and applies the same size comparisons to detect downward liquidity grabs.
- **Candle Highlighting:**
- If the conditions for a liquidity grab are met (both urgency and size), the script changes the bar color to green for upward liquidity and yellow for downward liquidity. These colored bars visually highlight the candles that meet the liquidity grab conditions.
- The script also colors up to three consecutive candles if they meet the liquidity grab conditions (offset = -1, -2).
#### 3. **Benefits of Using This Script:**
- **Liquidity Grab Detection:**
This script helps detect potential liquidity grabs, which occur when large players in the market push the price in a direction to trigger stop-losses or lure retail traders into a position before reversing the price direction. By detecting these movements, traders can avoid being trapped and potentially take advantage of the upcoming reversal.
- **Simple & Lightweight:**
The script uses basic inputs and calculations to detect liquidity grabs, making it easy to use and understand. It's less complex than the advanced version, which makes it suitable for traders who prefer simplicity or are new to liquidity grab detection.
- **Visual Clarity:**
The script uses color changes (green for upward grabs and yellow for downward grabs) to help traders easily spot potential liquidity grab areas on the chart. These visual cues make it more straightforward to interpret.
#### 4. **When to Use This Basic Version:**
- **Quick Liquidity Detection:** This script is ideal for traders who need a quick way to detect potential liquidity grabs without the complexity of managing dynamic parameters or volume confirmation.
- **Simplified Trading Strategies:** If your trading strategy doesn’t rely heavily on volume or multi-timeframe liquidity grab adjustments, this script can work well for basic setups where price action is the primary indicator.
- **Faster Execution:** Since this version doesn’t require dynamic adjustments or volume confirmation, it executes faster, making it suitable for traders who need lightweight tools to stay on top of fast-moving markets.
### Conclusion:
The basic version of the **Fx_Shepherd_Liquidity** script offers a simplified tool for detecting potential liquidity grabs. Its straightforward design, adjustable Maru rate, and visual bar color changes make it easy to integrate into any trading strategy focused on price action. While it lacks the advanced features of the premium version, it serves as a solid, lightweight solution for traders who prefer simplicity over complexity.
US30 Challenge 3.0Purpose of the Script
This script is designed to provide advanced technical analysis for the US30 index by combining moving averages (MA and EMA) on different timeframes and a modified Keltner channel to analyze volatility. It visualizes trends across both daily and hourly charts and displays their relationship in a custom table, helping traders to make informed decisions based on the alignment of these indicators.
Explanation of the Key Features
User Input Parameters:
The script allows users to customize several parameters, such as whether to show the baseline moving average, which type of moving average to use (e.g., EMA, SMA, HMA), and the length of the moving average. These inputs make the script flexible, allowing users to adjust it to their trading style.
Moving Averages (MA and EMA):
Two types of moving averages are calculated: the baseline (which can be any of several moving average types) and two additional moving averages (SMA and EMA) based on user-defined periods. These are plotted on the chart to provide insight into the trend and momentum of the US30 price action.
The baseline moving average is central to the strategy, and its calculation can be customized by selecting different methods (e.g., SMA, EMA, or HMA), making it adaptable to different market conditions.
Volatility Bands (Keltner Channel):
The script calculates volatility bands using a method similar to the Keltner Channel. It can either use the True Range (ATR) or the simple high-low price difference to determine market volatility.
These bands are useful for identifying overbought and oversold conditions, as well as detecting periods of price contraction or expansion. The width of the bands is adjustable via a multiplier, allowing users to fine-tune their analysis.
Security Function for Higher Timeframes:
The script retrieves moving average values for the daily timeframe using the request.security() function, which allows it to display higher-timeframe information on lower-timeframe charts. This gives traders a multi-timeframe perspective, helping them align their shorter-term trades with the broader trend.
Trend and Cross Detection:
The script detects when the EMA crosses below or above the SMA on both the daily and hourly timeframes. These crossovers are significant for trend-following strategies, as they often signal shifts in market momentum.
It visually indicates whether the EMA is above or below the SMA for both timeframes using color-coded panels, providing an easy-to-read summary of market conditions.
Custom Table Display:
A custom table is created to summarize the trend information for both the daily and hourly timeframes. The table shows whether the EMA is above or below the SMA for each timeframe, with green or red background colors indicating bullish or bearish conditions, respectively.
This feature is particularly useful for traders who want a quick, at-a-glance confirmation of the trend across multiple timeframes without having to analyze the chart visually.
Visual Plotting:
The script plots the moving averages and volatility bands directly on the price chart, providing clear visual cues for traders. The baseline and bands help traders identify key support and resistance levels, while the additional moving averages help confirm the current trend direction.
How to Use the Script
Adjust Parameters:
Before using the script, traders can customize the type of baseline moving average, its length, and the volatility band multiplier to suit their specific strategy and market conditions. Users can also choose whether to use the True Range or high-low difference for the volatility calculation.
Multi-Timeframe Analysis:
The script combines information from both daily and hourly charts, making it ideal for traders who prefer to align their short-term trades with the broader market trend. The custom table provides a quick snapshot of the trend on both timeframes, allowing users to see if the EMA is above or below the SMA in both cases.
Visual Cues:
By watching the relationship between price and the plotted bands, traders can identify potential breakouts, consolidations, or reversals. The moving average crossovers provide a simple, yet powerful, signal for entering or exiting trades.
Trend Confirmation:
The color-coded custom table helps traders quickly confirm the trend without having to analyze the price action directly. If both the daily and hourly EMA are above their respective SMA, this indicates a strong bullish trend. Conversely, if the EMA is below the SMA on both timeframes, this signals a bearish trend.
Differences from Other Scripts
Multi-Timeframe Cross Detection: Unlike many scripts, this one focuses on detecting moving average crossovers across multiple timeframes (daily and hourly), providing traders with a more comprehensive view of the market.
Custom Volatility Band Calculation: It includes a customizable Keltner-like channel, offering flexibility in how volatility is calculated, which is not commonly found in standard indicators.
Visual Trend Table: The addition of a custom table to visually display trend confirmation across different timeframes sets this script apart from most others, making it easier for traders to digest the information.
******************************************************************** (Español)
Propósito del Script
Este script está diseñado para proporcionar un análisis técnico avanzado del índice US30, combinando medias móviles (MA y EMA) en diferentes marcos de tiempo y un canal Keltner modificado para analizar la volatilidad. Visualiza las tendencias tanto en gráficos diarios como horarios y muestra su relación en una tabla personalizada, ayudando a los traders a tomar decisiones informadas basadas en la alineación de estos indicadores.
Explicación de las Características Clave
Parámetros de Entrada del Usuario:
El script permite a los usuarios personalizar varios parámetros, como si mostrar la media móvil base, qué tipo de media móvil usar (por ejemplo, EMA, SMA, HMA) y la longitud de la media móvil. Estos inputs hacen que el script sea flexible, permitiendo que los usuarios lo ajusten a su estilo de trading.
Medias Móviles (MA y EMA):
Se calculan dos tipos de medias móviles: la base (que puede ser de varios tipos) y dos medias adicionales (SMA y EMA) basadas en los períodos definidos por el usuario. Estas se trazan en el gráfico para proporcionar información sobre la tendencia y el impulso de la acción del precio del US30.
La media móvil base es central en la estrategia, y su cálculo se puede personalizar seleccionando diferentes métodos (por ejemplo, SMA, EMA, o HMA), lo que la hace adaptable a diferentes condiciones de mercado.
Bandas de Volatilidad (Canal Keltner):
El script calcula bandas de volatilidad usando un método similar al Canal Keltner. Puede usar el Rango Verdadero (ATR) o la simple diferencia entre el alto y el bajo del precio para determinar la volatilidad del mercado.
Estas bandas son útiles para identificar condiciones de sobrecompra y sobreventa, así como para detectar períodos de contracción o expansión del precio.
Función security() para Tiempos Superiores:
El script obtiene los valores de las medias móviles para el marco temporal diario, utilizando la función request.security(), lo que permite mostrar información de marcos temporales más largos en gráficos de marcos más cortos.
Detección de Cruces de Tendencia:
El script detecta cuando la EMA cruza por debajo o por encima de la SMA en los gráficos diarios y horarios. Estos cruces son significativos para estrategias de seguimiento de tendencias, ya que suelen señalar cambios en el impulso del mercado.
Tabla de Tendencias Personalizada:
Se crea una tabla personalizada para resumir la información de la tendencia en los gráficos diarios y horarios, mostrando si la EMA está por encima o por debajo de la SMA.
Trazado Visual:
El script traza las medias móviles y las bandas de volatilidad directamente en el gráfico de precios, proporcionando señales visuales claras para los traders.
Cómo usar el Script
Ajustar Parámetros.
Análisis Multi-Tiempo.
Señales Visuales.
Confirmación de Tendencia.
Diferencias con Otros Scripts
Detección Multi-Tiempo de Cruces.
Cálculo Personalizado de Bandas de Volatilidad.
Tabla Visual de Tendencia.
Saludos
VM y CS
The real breakout indicator CCI + Money Flow + Buy / SellComponents of the indicator
1. CCI (Commodity Channel Index)
The CCI component measures the deviation of the price from its statistical average. It is used to identify overbought or oversold conditions and is integrated into the trend logic to determine potential trend reversals. High values may indicate overbought conditions, while low values could signify oversold situations.
Detailed
The CCI (Commodity Channel Index) used in "The Real Breakout Indicator Hawk" is an enhanced version compared to the traditional CCI, offering several advantages:
1. Weighting and Smoothing Mechanism
In this version, the CCI values are weighted and smoothed using custom parameters (c1, c2, c3), which allows for greater flexibility in adjusting the sensitivity of the CCI to market conditions. This smoothing reduces noise and provides clearer signals compared to the standard CCI, which can be prone to whipsaws in volatile markets.
2. Multi-level Calculation
The indicator uses an array-based approach to calculate multiple variations of CCI values (with p as the parameter for different levels of calculation), which is then combined to create a more robust signal. This multi-level approach allows for capturing different market cycles, unlike the traditional CCI that only uses a single period for calculation.
3. Integration with Moving Averages and Trend Detection
Unlike the original CCI, which is often used in isolation, this version integrates with the trend detection logic by combining it with moving averages and money flow. The enhanced CCI contributes to the broader trend analysis, ensuring that buy/sell signals are not just based on CCI overbought/oversold levels but also validated by moving averages and slope calculations.
4. Trend-Weighted CCI
This version adds weight to recent price action trends, making it more adaptive to current market momentum. The CCI values are influenced by recent high and low prices, adding a trend-following aspect that is missing from the original CCI, which treats all price deviations equally.
This image of EURAD shows for example that when CCI component is green a strong trend is detected which can hold for up to 10 days in this example, ideal for swing trades;
EURAUD 2H
5. Improved Overbought/Oversold Detection
The script incorporates a dynamic overbought/oversold detection zone based on the enhanced CCI. It accounts for market volatility, allowing it to adjust its thresholds (such as the 200 level) more effectively in different market environments. This makes the enhanced CCI better suited for varying market conditions compared to the fixed thresholds of the original CCI.
You can see that the red diamond signal is generated at the absolute top of the price range after which price started to reverse, the detection is based on a cross over value together with Money Flow strength
BTCUSDT 2H
6. Strong Buy/Sell Confirmation
The enhanced CCI works in tandem with other components like Money Flow and Moving Averages to confirm buy or sell signals. This cross-validation makes the indicator less reliant on CCI alone and ensures that the signals generated are stronger and less prone to false positives, which is a common issue with the standalone CCI.
The green diamond buy signal in a strong downtrend is mostly a short retrace of price before continuing down further, yo can use this as an entry signal after the bounce up into an FVG for example. However when price is at a support, meaning price is not moving down further and this occurs this could be a potential reversal signal as shown on the right side on the chart below. FVG is not respected, retested and price continues up.
BTCUSDT 2H
Summary:
In summary, the enhanced CCI in this indicator improves over the original CCI by providing better noise reduction, multi-level analysis, trend integration, and adaptability to different market conditions. These improvements lead to more reliable and actionable trading signals.
2. Money Flow (MF) www.tradingview.com
The Money Flow component tracks the flow of capital in and out of an asset. Positive values indicate strong buying pressure, while negative values show selling pressure. This is smoothed to avoid noise and is used to confirm strong buy or sell conditions.
The Money Flow (MF) in "The Real Breakout Indicator Hawk" measures the flow of capital into or out of an asset, helping to assess the underlying buying or selling pressure in the market.
1. Positive Money Flow (Buying Pressure)
When the MF is positive, it indicates that more money is flowing into the asset, which suggests strong buying interest. This helps confirm that a price increase or breakout to the upside is supported by demand.
2. Negative Money Flow (Selling Pressure)
A negative MF indicates that capital is leaving the asset, reflecting selling pressure. This is a sign that the market is under bearish conditions, and prices are likely to decline or break down.
3. Confirmation of Buy and Sell Signals
The MF is used to confirm buy and sell signals generated by other components of the indicator. When the MF aligns with other bullish signals, it strengthens the buy condition, and similarly, when the MF shows strong selling pressure, it reinforces a sell signal.
4. Filtering Noise
The MF is smoothed to filter out noise, ensuring that only significant movements in buying or selling pressure are considered. This helps avoid false signals and makes the MF a reliable tool for detecting true market strength.
5. Range Sensitivity
The MF operates within defined ranges, ensuring that buy or sell signals are only triggered when the flow of money is strong enough, adding precision to signal generation.
In summary, the Money Flow component is crucial for validating market direction, enhancing signal reliability, and helping traders make more informed decisions based on the underlying capital movement in the market.
3. Moving Averages (MA)
Multiple types of moving averages (SMA, EMA, HMA, etc.) are used to smooth price action and highlight the trend direction. The script supports different types of moving averages, and their slopes are calculated to assist in identifying changes in trend momentum.
The Moving Averages (MA) section of "The Real Breakout Indicator Hawk" plays a critical role in smoothing price data, identifying trends, and generating buy/sell signals. Here’s a breakdown of what it does and how you can use it effectively without diving into the script:
1. Moving Average Types
This section allows the user to choose from different types of moving averages, each with unique characteristics:
SMA (Simple Moving Average): Takes the average of closing prices over a specific period. It’s slower and better suited for detecting long-term trends.
EMA (Exponential Moving Average): Gives more weight to recent prices, making it more responsive to new price action and suitable for short-term trading.
HMA (Hull Moving Average): A smoother and faster moving average, useful for reducing lag in fast-moving markets.
LVMA (Linear Weighted Moving Average): Places the most weight on recent prices, making it even more responsive than EMA.
Alma (Arnaud Legoux Moving Average): A smoother version that reduces noise while maintaining responsiveness to recent price action.
2. Smoothing and Trend Detection
The moving average smooths out price data to remove small fluctuations and focuses on the overall trend. When prices are trading above the moving average, it suggests that the market is in an uptrend. When prices are below the moving average, it indicates a downtrend.
3. Trend Confirmation
The moving average serves as a confirmation tool. When the price crosses above the moving average, it could signal the start of a bullish trend, and when the price crosses below, it may indicate the beginning of a bearish trend.
4. Buy and Sell Signals
Buy Signal: The system detects a buy signal when:
The moving average crosses above 0, indicating a potential upward momentum.
Other indicators like Money Flow and CCI align to confirm the trend.
Sell Signal: A sell signal is triggered when:
The moving average crosses below 0, signaling a potential downtrend.
This signal is further validated by other components such as Money Flow and CCI to reduce false signals.
5. Using Moving Averages in Trading
Crossover Strategy: One of the simplest ways to use moving averages is by employing a crossover strategy. For instance:
When the shorter-term moving average (e.g., 20-period) crosses above a longer-term moving average (e.g., 50-period), this is a bullish crossover, indicating a buy signal.
Conversely, when the shorter-term moving average crosses below the longer-term moving average, this is a bearish crossover, indicating a sell signal.
Trend Following: If you’re trading with the trend, you can use a moving average to stay in the trade as long as the price remains above (for long positions) or below (for short positions) the moving average.
Support and Resistance: Moving averages can also act as dynamic support or resistance levels. For example, in an uptrend, the CCI might bounce off the moving average, offering a good entry point for a long position. In a downtrend, the moving average could act as resistance where prices may reverse, offering a shorting opportunity.
To use the MA section effectively:
Choose the right type of moving average based on your trading style (e.g., use EMA for faster response or SMA for long-term trends).
Watch for crossovers as buy/sell signals, especially in combination with other indicators.
Follow the trend by observing whether the price is above or below the moving average.
Use the moving average as a dynamic support/resistance level to find optimal entry/exit points.
This approach makes the moving average a versatile tool for identifying trends, refining entry and exit points, and confirming overall market direction.
an example when MA crosses below 0, keep in mind that when it it starts curving up and turning green there is a reversal brewing, this could take time...
BTCUSDT 2H
4. Buy Signals
Buy signals are generated when the moving average crosses up, and the Money Flow and other trend-based conditions are met, including CCI levels confirming the strength of the breakout. Additionally, slope calculations and other momentum indicators provide extra confirmation for entries.
5. Sell Signals
Sell signals occur when the moving average crosses down, combined with negative Money Flow, confirming downward pressure. Other trend-based conditions, including the CCI, must also align to validate the signal, and slope calculations ensure that momentum is on the sell side.
6. Slope and Trend Detection
The script includes calculations for the slope of price action over a lookback period to measure trend strength and direction. The slope is normalized to help identify when the market is gaining or losing momentum. This slope is used in conjunction with the moving averages and Money Flow to give more accurate trend signals.
The Slope and Trend Detection component in "The Real Breakout Indicator Hawk" is designed to measure the direction and strength of the market’s trend by calculating the slope of the price action over a specific period. This helps to identify whether the market is gaining or losing momentum, and it is a key element in refining buy/sell signals.
Here’s how the Slope and Trend Detection works and how you can use it effectively without diving into the script:
1. Slope Calculation
Slope is essentially the rate of change of the moving average (or price) over a given number of bars. It measures how steeply the price is moving up or down.
The script calculates the slope by measuring the difference between the moving average over a defined number of bars (e.g., 12 bars in this case). A larger slope indicates a stronger trend, while a smaller slope suggests a weaker or consolidating trend.
2. Normalized Slope
The slope is normalized, meaning it is adjusted to fall within a range that makes it easier to compare across different time frames and markets. This normalization helps to gauge whether the slope is strong or weak relative to historical data.
Positive slopes (above 0) indicate an uptrend or rising price momentum, while negative slopes (below 0) indicate a downtrend or falling price momentum.
3. Trend Detection
The slope of the moving average is used to detect the current trend:
If the slope is positive, the market is in an uptrend.
If the slope is negative, the market is in a downtrend.
The stronger the slope (the steeper it is), the stronger the trend. A small slope indicates a weak trend or consolidation.
4. Slope Thresholds
The system uses thresholds to determine the significance of the slope. These thresholds are set as upper and lower bounds:
Upper Threshold: If the slope exceeds this threshold, the trend is considered strong, and it could trigger a buy signal.
Lower Threshold: If the slope falls below this threshold (into the negative range), it indicates a strong downtrend, and it could trigger a sell signal.
These thresholds help filter out weak or false signals that occur in sideways or low-momentum markets.
5. Positive and Negative Slope Arrays
The system keeps track of both positive and negative slopes over a defined lookback period (e.g., 500 bars). By storing these values, it creates a historical context that helps to assess the current slope in relation to past price movements.
It calculates the standard deviation and the average of these slopes to dynamically adjust the thresholds for each market condition, making the trend detection more adaptive to different types of assets or market phases.
6. Using Slope and Trend Detection in Trading
Buy Signal with Positive Slope: When the slope is positive and exceeds a certain threshold, it confirms that the market is in a strong uptrend. This can be used as a signal to enter a long position or add to existing long trades.
Sell Signal with Negative Slope: When the slope turns negative and falls below the lower threshold, it signals a strong downtrend, indicating a potential short-selling opportunity or the time to exit long positions.
Avoiding Flat Markets: If the slope remains close to zero (neither strongly positive nor negative), it suggests a lack of clear trend or a consolidating market. In these conditions, it might be better to avoid taking new trades or use additional filters to confirm signals.
7. Slope-Based Trend Strength Indicator
You can also use the slope as a measure of trend strength:
Strong Trend: When the slope is steep (either positive or negative), it indicates strong momentum, and you can be more confident in holding a trade in that direction.
Weak Trend or Consolidation: When the slope is flat, it indicates weak price momentum, which may signal a period of consolidation or indecision in the market.
8. Visual Representation
The slope is often visually represented as a gradient or line that fluctuates around a central point (usually zero). Positive values are shown in one color (e.g., green for an uptrend), while negative values are shown in another color (e.g., red for a downtrend). This allows traders to quickly identify the current trend direction and its strength.
Summary:
To use Slope and Trend Detection effectively:
Monitor the slope to determine the trend direction (positive = uptrend, negative = downtrend).
Look for thresholds to identify strong trends. For instance, a steep positive slope signals a strong uptrend, while a steep negative slope signals a strong downtrend.
Use slope changes to confirm buy/sell signals. For example, if you receive a buy signal and the slope is positive and increasing, it confirms that momentum is behind the trade.
Avoid low-slope periods when the slope is close to zero, indicating a lack of trend or sideways market conditions.
This approach helps traders stay on the right side of the trend while avoiding periods of low momentum, enhancing the accuracy of trade signals.
7. Banker Fund Flow Trend
This component identifies potential large institutional moves by tracking specific patterns in price and volume data. When the institutional or "banker" entry or exit conditions are met, it highlights these moments with candles and generates alerts.
The Banker Fund Flow Trend in "The Real Breakout Indicator Hawk" helps detect the flow of institutional (or "smart money") into and out of the market by tracking price trends and large player activity. It uses red and yellow candles to signal when institutional money is influencing the market.
Key Points:
Yellow Candles (Banker Entry):
A yellow candle is plotted when institutional money starts flowing into the market.
This signals a potential buy opportunity, as large market players are likely pushing prices upward.
Red Candles (Banker Exit):
A red candle appears when institutional money starts exiting the market.
This is a signal to consider selling or exiting long positions, as institutional selling could drive prices lower.
Usage:
Yellow candles: Use these as signals to enter long trades or add to existing positions, confirming upward momentum driven by institutional buyers.
Red candles: Treat these as signals to exit long trades or consider short positions, as institutional selling may lead to further downside.
BTCUSDT 2H
The yellow and red candles provide clear, actionable signals for aligning trades with institutional flows, ensuring you’re following the "smart money."
8. Dynamic Buy/Sell Calculations
A dynamic component is designed to refine the buy and sell signals further based on additional conditions like price patterns, volatility, and Money Flow. This ensures that signals are more responsive to changing market conditions.
The Dynamic Buy/Sell Calculations in "The Real Breakout Indicator Hawk" are designed to refine entry and exit points for trades by using additional conditions beyond simple crossovers. These calculations adapt to the current market conditions, making them more responsive to changes in volatility, trend strength, and momentum.
Key Features:
Dynamic Buy Calculation:
The indicator generates a buy signal when multiple conditions align. These conditions include the money flow (MF) being within a favorable range, the moving average (MA) confirming upward momentum, and the CCI and other trend components indicating strength.
This makes the buy signal more reliable, as it considers multiple aspects of market behavior (price, momentum, and money flow) to avoid false entries.
Dynamic Sell Calculation:
Similarly, the sell signal is triggered when the dynamic conditions indicate downward momentum.
This includes:
The moving average crossing down.
Negative money flow, suggesting selling pressure.
Other trend signals confirming a bearish move.
The dynamic nature of these conditions ensures that sell signals are only generated when there’s a high probability of continued downside movement.
Adaptive to Market Conditions:
The dynamic nature of these calculations means that the buy/sell signals adapt to market changes, like volatility spikes or sudden trend reversals. Instead of relying on static conditions, the system adjusts to current price movements and volatility.
Avoiding Noise:
By adding multiple filters like MF thresholds, slope, and moving averages, the dynamic calculations help reduce false signals that occur in noisy, sideways markets. This helps traders avoid entering trades during periods of low momentum or unclear trends.
How to Use:
Buy Signals: Use these signals to enter long trades when the dynamic conditions align, confirming that upward momentum is strong and backed by institutional flows.
BTCUSDT 2H
Aqua marker/cross signals (price manipulation/continuation)
BTCUSDT 2H
Sell Signals: Use the sell signals to exit long positions or enter short trades when the market shows signs of bearish momentum, confirmed by multiple conditions like MA crossovers and negative money flow.
BTCUSDT 2H
In summary, the Dynamic Buy/Sell Calculations provide a more sophisticated approach to generating trade signals by combining various trend and momentum indicators, helping traders make more informed decisions in different market conditions.
This part of the code is identifying two key trading signals: moments to buy and moments to sell based on the behavior of a calculated trend line.
Buy Condition:
The system looks for a situation where the trend has been moving downward but has started to reverse upward. Specifically, it checks if the trend was declining a little while ago, then stopped falling, and is now starting to rise. If these conditions are met and the trend is still below a certain level, the system considers this a possible time to buy.
Sell Condition:
The opposite happens for selling. The system monitors for a situation where the trend has been moving upward but starts to turn downward. It checks if the trend was rising, leveled off, and now seems to be starting to fall. If these conditions are met and the trend is above a certain level, this could indicate a good time to sell.
Visual Markers:
To help the user easily see these signals on a chart, the system places symbols at specific points. A marker appears on the chart where the conditions for buying or selling are met, allowing the trader to quickly spot potential entry or exit points in the market.
In summary, this logic is designed to detect possible changes in trend direction and signal appropriate times to consider buying or selling, with clear visual markers on the chart for quick identification.
9. Alerts for Buy and Sell
The indicator provides built-in alert conditions for both buy and sell signals. When these conditions are met, the system generates alerts, making it suitable for automated monitoring.
Each of these components works together to detect potential breakout opportunities, trend continuations, and reversals, making the indicator suitable for both short-term and long-term trading strategies.
MACD with DPO Strategy by NGExplanation of the MACD with DPO Strategy:
MACD (Moving Average Convergence Divergence):
The MACD is a trend-following indicator that shows the relationship between two moving averages of a price.
In this script:
We calculate the MACD line by subtracting the slow moving average (typically 26-period EMA) from the fast moving average (typically 12-period EMA).
The Signal line is calculated as a 9-period EMA of the MACD line.
The Histogram is the difference between the MACD line and the Signal line, indicating the momentum of the price trend.
Buy Condition: The script generates a buy signal when the MACD histogram crosses from negative to positive (indicating a bullish momentum) and DPO is also positive.
Sell Condition: The script generates a sell signal when the MACD histogram crosses from positive to negative (indicating a bearish momentum) and DPO is also negative.
DPO (Detrended Price Oscillator):
The DPO removes long-term trends from prices, making it easier to identify shorter-term cycles or oscillations.
In this script:
We calculate the DPO by subtracting a shifted simple moving average (SMA) from the close price. The shifting period depends on half the specified period.
We also calculate the DPO SMA as a 30-period EMA of the DPO values.
DPO Color: The DPO line is colored green when the DPO is above zero (indicating upward momentum) and red when it is below zero (indicating downward momentum). The histogram is also colored based on whether the DPO is positive or negative.
Plotting and Alerts:
The script plots the MACD, Signal, and Histogram on the chart.
Additionally, it plots the DPO and its SMA with different colors depending on whether the DPO is above or below zero.
Buy Signal: A green arrow labeled "BUY" is plotted below the bar when both MACD and DPO indicate a bullish condition.
Sell Signal: A red arrow labeled "SELL" is plotted above the bar when both MACD and DPO indicate a bearish condition.
Background colors are used to highlight the chart whenever a buy or sell condition occurs.
The script also includes alerts for both buy and sell signals, allowing users to set notifications when conditions are met.
How to Use:
Identify Buy and Sell Signals:
The script generates a Buy signal when:
The MACD histogram crosses from negative to positive (bullish momentum), and
The DPO is above zero (indicating upward momentum).
The script generates a Sell signal when:
The MACD histogram crosses from positive to negative (bearish momentum), and
The DPO is below zero (indicating downward momentum).
Chart Visualization:
The MACD histogram and Signal line help visualize the momentum and potential trend reversal.
The DPO and DPO SMA help visualize the shorter-term price cycles.
The signals (Buy and Sell) will be plotted on the chart with arrows indicating entry points.
Customization:
You can adjust the MACD and DPO parameters (such as fast_length, slow_length, period_) to fit your trading style or market conditions.
The script can be used in any timeframe depending on your strategy (e.g., intraday trading or longer-term trading).
Example Scenario:
If you're looking for potential buy opportunities, wait for the script to generate a buy signal (green arrow) where the MACD histogram has shifted to positive, and DPO is also in the green (above zero). This signals that both momentum and cycle direction are aligned for a potential upward movement.
Conversely, for sell opportunities, wait for the red arrow where MACD momentum is turning negative and DPO is also negative (below zero), indicating a bearish condition.
This combination of MACD and DPO allows traders to identify stronger and more reliable entry/exit points by confirming the trend with the MACD and detecting shorter-term price cycles with the DPO.
Ticker Tape█ OVERVIEW
This indicator creates a dynamic, scrolling display of multiple securities' latest prices and daily changes, similar to the ticker tapes on financial news channels and the Ticker Tape Widget . It shows realtime market information for a user-specified list of symbols along the bottom of the main chart pane.
█ CONCEPTS
Ticker tape
Traditionally, a ticker tape was a continuous, narrow strip of paper that displayed stock prices, trade volumes, and other financial and security information. Invented by Edward A. Calahan in 1867, ticker tapes were the earliest method for electronically transmitting live stock market data.
A machine known as a "stock ticker" received stock information via telegraph, printing abbreviated company names, transaction prices, and other information in a linear sequence on the paper as new data came in. The term "ticker" in the name comes from the "tick" sound the machine made as it printed stock information. The printed tape provided a running record of trading activity, allowing market participants to stay informed on recent market conditions without needing to be on the exchange floor.
In modern times, electronic displays have replaced physical ticker tapes. However, the term "ticker" remains persistent in today's financial lexicon. Nowadays, ticker symbols and digital tickers appear on financial news networks, trading platforms, and brokerage/exchange websites, offering live updates on market information. Modern electronic displays, thankfully, do not rely on telegraph updates to operate.
█ FEATURES
Requesting a list of securities
The "Symbol list" text box in the indicator's "Settings/Inputs" tab allows users to list up to 40 symbols or ticker Identifiers. The indicator dynamically requests and displays information for each one. To add symbols to the list, enter their names separated by commas . For example: "BITSTAMP:BTCUSD, TSLA, MSFT".
Each item in the comma-separated list must represent a valid symbol or ticker ID. If the list includes an invalid symbol, the script will raise a runtime error.
To specify a broker/exchange for a symbol, include its name as a prefix with a colon in the "EXCHANGE:SYMBOL" format. If a symbol in the list does not specify an exchange prefix, the indicator selects the most commonly used exchange when requesting the data.
Realtime updates
This indicator requests symbol descriptions, current market prices, daily price changes, and daily change percentages for each ticker from the user-specified list of symbols or ticker identifiers. It receives updated information for each security after new realtime ticks on the current chart.
After a new realtime price update, the indicator updates the values shown in the tape display and their colors.
The color of the percentages in the tape depends on the change in price from the previous day . The text is green when the daily change is positive, red when the value is negative, and gray when the value is 0.
The color of each displayed price depends on the change in value from the last recorded update, not the change over a daily period. For example, if a security's price increases in the latest update, the ticker tape shows that price with green text, even if the current price is below the previous day's closing price. This behavior allows users to monitor realtime directional changes in the requested securities.
NOTE: Pine scripts execute on realtime bars when new ticks are available in the chart's data feed. If no new updates are available from the chart's realtime feed, it may cause a delay in the data the indicator receives.
Ticker motion
This indicator's tape display shows a list of security information that incrementally scrolls horizontally from right to left after new chart updates, providing a dynamic visual stream of current market data. The scrolling effect works by using a counter that increments across successive intervals after realtime ticks to control the offset of each listed security. Users can set the initial scroll offset with the "Offset" input in the "Settings/Inputs" tab.
The scrolling rate of the ticker tape display depends on the realtime ticks available from the chart's data feed. Using the indicator on a chart with frequent realtime updates results in smoother scrolling. If no new realtime ticks are available in the chart's feed, the ticker tape does not move. Users can also deactivate the scrolling feature by toggling the "Running" input in the indicator's settings.
█ FOR Pine Script™ CODERS
• This script utilizes dynamic requests to iteratively fetch information from multiple contexts using a single request.security() instance in the code. Previously, `request.*()` functions were not allowed within the local scopes of loops or conditional structures, and most `request.*()` function parameters, excluding `expression`, required arguments of a simple or weaker qualified type. The new `dynamic_requests` parameter in script declaration statements enables more flexibility in how scripts can use `request.*()` calls. When its value is `true`, all `request.*()` functions can accept series arguments for the parameters that define their requested contexts, and `request.*()` functions can execute within local scopes. See the Dynamic requests section of the Pine Script™ User Manual to learn more.
• Scripts can execute up to 40 unique `request.*()` function calls. A `request.*()` call is unique only if the script does not already call the same function with the same arguments. See this section of the User Manual's Limitations page for more information.
• This script converts a comma-separated "string" list of symbols or ticker IDs into an array . It then loops through this array, dynamically requesting data from each symbol's context and storing the results within a collection of custom `Tape` objects . Each `Tape` instance holds information about a symbol, which the script uses to populate the table that displays the ticker tape.
• This script uses the varip keyword to declare variables and `Tape` fields that update across ticks on unconfirmed bars without rolling back. This behavior allows the script to color the tape's text based on the latest price movements and change the locations of the table cells after realtime updates without reverting. See the `varip` section of the User Manual to learn more about using this keyword.
• Typically, when requesting higher-timeframe data with request.security() using barmerge.lookahead_on as the `lookahead` argument, the `expression` argument should use the history-referencing operator to offset the series, preventing lookahead bias on historical bars. However, the request.security() call in this script uses barmerge.lookahead_on without offsetting the `expression` because the script only displays results for the latest historical bar and all realtime bars, where there is no future information to leak into the past. Instead, using this call on those bars ensures each request fetches the most recent data available from each context.
• The request.security() instance in this script includes a `calc_bars_count` argument to specify that each request retrieves only a minimal number of bars from the end of each symbol's historical data feed. The script does not need to request all the historical data for each symbol because it only shows results on the last chart bar that do not depend on the entire time series. In this case, reducing the retrieved bars in each request helps minimize resource usage without impacting the calculated results.
Look first. Then leap.
Risk Management Calculator with Fees and Take Profit [CHE]Risk Management Calculator with Fees and Take Profit
Welcome to the Risk Management Calculator with Fees and Take Profit script! This powerful tool is designed to help traders manage their risk effectively, calculate leverage, and set take profit targets. The script is inspired by and builds upon the ideas from the following TradingView script: ().
This script is inspired by and builds upon the ideas from the following TradingView script:
Features
1. Portfolio Size Input: Enter the size of your portfolio to accurately calculate your risk and leverage.
2. Max Loss Percent Input: Specify the maximum percentage of your portfolio that you are willing to risk on a single trade.
3. Max Leverage Input: Set the maximum leverage you are comfortable using.
4. Trading Fee Input: Include trading fees in your calculations to get a more realistic view of your potential losses and gains.
5. ATR Settings: Configure the ATR period and multiplier to calculate your stop loss and take profit levels.
6. RSI Settings: Adjust the RSI period for trend analysis.
How to Use
Portfolio Size
- Description: This is the total value of your trading account.
- Input: `portfolioSize`
- Default Value: 100
- Minimum Value: 0.001
Max Loss Percent
- Description: The maximum percentage of your portfolio you are willing to lose on a single trade.
- Input: `maxLossPercent`
- Default Value: 3%
- Range: 0.1% to 100%
Max Leverage
- Description: The maximum leverage you wish to use.
- Input: `maxLeverage`
- Default Value: 125
- Range: 1 to 125
Trading Fee
- Description: The fee percentage you pay per trade.
- Input: `feeRate`
- Default Value: 1%
- Range: 0% to 10%
ATR Settings
- ATR Period: Number of bars used to calculate the Average True Range.
- Input: `atrPeriod`
- Default Value: 5
- ATR Multiplier: Multiplier for ATR to set stop loss levels.
- Input: `atrMultiplier`
- Default Value: 2.0
Take Profit Multiplier
- Description: Multiplier for ATR to set take profit levels.
- Input: `takeProfitMultiplier`
- Default Value: 2.0
RSI Settings
- RSI Period: Period for the RSI calculation.
- Input: `rsiPeriod`
- Default Value: 14
Dashboard
The script includes a customizable dashboard that displays the following information:
- Portfolio Size
- Maximum Loss Amount
- Entry Price
- Stop Loss Price
- Stop Loss Percentage
- Calculated Leverage
- Order Value
- Order Quantity
- Trend Direction
- Adjusted Maximum Loss Percentage
- Take Profit Price
Dashboard Settings
- Location: Choose the position of the dashboard on the chart.
- Options: 'Top Right', 'Bottom Right', 'Top Left', 'Bottom Left'
- Size: Adjust the size of the dashboard text.
- Options: 'Tiny', 'Small', 'Normal', 'Large'
- Text/Frame Color: Set the color for the text and frame of the dashboard.
Underlying Principles and Assumptions
Leverage Calculation
The leverage calculation is fundamental to risk management in trading. It ensures that the risk per trade does not exceed a specified percentage of the portfolio. This calculation takes into account the potential loss from the entry price to the stop loss level, adjusted for trading fees. By dividing the maximum acceptable loss by the total potential loss (including fees), we derive a leverage that limits the exposure per trade. This approach helps traders avoid over-leveraging, which can lead to significant losses.
ATR and Stop Loss
The Average True Range (ATR) is used to set stop loss levels because it measures market volatility. A higher ATR indicates more volatility, which means wider stop losses are needed to avoid being prematurely stopped out by normal market fluctuations. By using an ATR multiplier, the stop loss is dynamically adjusted based on current market conditions, providing a more robust risk management strategy.
Take Profit Calculation
The take profit level is calculated as a multiple of the ATR, ensuring that it is set at a realistic level relative to market volatility. This method aims to capture significant price movements while avoiding the noise of smaller fluctuations. Setting take profit targets this way helps in locking in profits when the market moves favorably.
RSI for Trend Confirmation
The Relative Strength Index (RSI) is used to confirm the trend direction. An RSI above 50 typically indicates a bullish trend, while an RSI below 50 indicates a bearish trend. By aligning trades with the prevailing trend, the script increases the probability of successful trades. This trend confirmation helps in making informed decisions about leverage and position sizing.
Risk Color Coding
The script uses color coding to visually indicate the risk level and trend direction. Green indicates a favorable condition for long trades, red for short trades, and gray for neutral conditions. This intuitive color coding aids in quickly assessing the market conditions and making timely trading decisions.
Conclusion
This script aims to provide a comprehensive risk management tool for traders. By integrating portfolio size, leverage, fees, ATR, and RSI, it helps in making informed trading decisions. We hope you find this tool useful in your trading journey.
Happy Trading!
Daniels Script v2 EMA 4h y DTitle:
"EMA 200 Dynamic Projection on 4H and Daily Charts"
Description:
"This script is designed to provide traders with a comprehensive view of market trends by displaying the 200-period Exponential Moving Average (EMA) on both 4-hour and daily charts simultaneously. Unlike typical EMA representations, this script enhances user decision-making by projecting the potential future path of these EMAs using a dynamic slope calculation.
The dynamic projection feature calculates the slope based on recent changes in the EMA, allowing traders to visualize potential future trends more accurately. This innovative approach helps in identifying potential areas of support and resistance before they are fully formed, offering traders a strategic advantage in planning their entries and exits.
Key Features:
Dual Time Frame Analysis: View 200-period EMAs for both 4-hour and daily charts on a single graph.
Dynamic EMA Projections: Projected using a calculated slope from recent EMA changes, presented as dotted lines for clear distinction.
Enhanced Trend Visualization: Helps in recognizing trend continuations or reversals early, aiding in risk management and decision-making processes.
Usage:
Simply add the script to your chart, and the EMAs along with their projections will automatically be displayed. The 4-hour EMA is shown in green, while the daily EMA is in red. Projections extend from the last known data point, providing a visual guide to potential future movements.
This script is unique in its approach to combining real-time EMA analysis with predictive modeling, making it a valuable tool for traders looking to enhance their technical analysis capabilities."
## SPANISH
Título del Script:
"Proyección Dinámica de la EMA 200 en Gráficos de 4H y Diarios"
Descripción del Script:
"Este script está diseñado para proporcionar a los traders una visión integral de las tendencias del mercado al mostrar la Media Móvil Exponencial (EMA) de 200 periodos tanto en los gráficos de 4 horas como diarios simultáneamente. A diferencia de las representaciones típicas de la EMA, este script mejora la toma de decisiones del usuario al proyectar el posible camino futuro de estas EMAs utilizando un cálculo de pendiente dinámico.
La función de proyección dinámica calcula la pendiente basada en cambios recientes en la EMA, permitiendo a los traders visualizar tendencias futuras potenciales con mayor precisión. Este enfoque innovador ayuda a identificar áreas potenciales de soporte y resistencia antes de que se formen completamente, ofreciendo a los traders una ventaja estratégica en la planificación de sus entradas y salidas.
Características Clave:
Análisis de Doble Marco Temporal: Visualiza las EMAs de 200 periodos para los gráficos de 4 horas y diarios en un solo gráfico.
Proyecciones Dinámicas de la EMA: Proyectadas utilizando una pendiente calculada a partir de cambios recientes en la EMA, presentadas como líneas punteadas para una clara distinción.
Visualización Mejorada de Tendencias: Ayuda en el reconocimiento temprano de continuaciones o reversos de tendencias, asistiendo en la gestión de riesgos y en los procesos de toma de decisiones.
Uso:
Simplemente añade el script a tu gráfico, y las EMAs junto con sus proyecciones se mostrarán automáticamente. La EMA de 4 horas se muestra en verde, mientras que la EMA diaria está en rojo. Las proyecciones se extienden desde el último punto de datos conocido, proporcionando una guía visual hacia movimientos futuros potenciales.
Este script es único en su enfoque de combinar análisis de EMA en tiempo real con modelado predictivo, convirtiéndolo en una herramienta valiosa para traders que buscan mejorar sus capacidades de análisis técnico."
Triple MA HTF strategy - Dynamic SmoothingThe triple MA strategy is a simple but effective method to trade the trend. The advantage of this script over the existing triple MA strategies is that the user can open a lower time frame chart and select higher time frame inputs for different MA types mainting the visibility on the chart. The dynamic smoothing code makes sure the HTF trendlines are not jagged, but a fluid line visiable on the lower time frame chart. The script comes with a MA crossover and crossunder strategy explained below.
Moving Averages (MA) Crossover for Entry:
Long Entry: A long entry signal is triggered when the moving average line 1 crosses above the moving average line 2. This crossover indicates a potential shift in market sentiment towards the upside. However, to validate this signal, the strategy checks if the moving average 3 on a higher time frame (eg. 4 hour) is in an upward trend. This additional filter ensures that the trade aligns with the prevailing trend on a broader time scale, increasing the probability of success.
Short Entry: Conversely, a short entry signal occurs when the moving average line 1 crosses below the moving average line 2. This crossover suggests a possible downturn in market momentum. However, for a short trade to be confirmed, the strategy verifies that the moving average 3 on the higher time frame is in a downward trend. This confirmation ensures that the trade is in harmony with the overarching market direction.
Exit from Long Position: The strategy triggers an exit signal from a long position when the moving average line 1 crosses below the moving average line 2. This crossover indicates a potential reversal in the market trend, prompting the trader to close their long position and take profits or minimize losses.
Exit from Short Position: Similarly, an exit signal from a short position occurs when the moving average line 1 crosses above the moving average line 2. This crossover suggests a potential shift in market sentiment towards the upside, prompting the trader to exit their short position and manage their risk accordingly.
Features of the script
This Triple MA Strategy is basically the HTF Trend Filter displayed 3 times on the chart. For more infomation on how the MA with dynamic smoothing is calculated I recommend reading the following script:
For risk management I included a simple script to opt for % of eauity or # of contracts of in the instrument. For explanation on how the risk management settings work I refer to my ealier published script:
The strategy is a simplified example for setting up an entry and exit logic based on multiple moving avarages. Hence the script is meant for educational purposes only.
Ichimoku Slope Filtered Signals [UAlgo]
🔶Description:
The "Ichimoku Slope Filtered Signals" indicator is designed to provide trading signals based on the Ichimoku Cloud indicator while incorporating a slope filter. The Ichimoku Cloud is a comprehensive indicator that defines support and resistance, identifies trend direction, and provides trading signals. This script enhances the traditional Ichimoku Cloud signals by incorporating a slope filter, which helps to confirm the strength and direction of the trend.
🔶Key Features:
Ichimoku Cloud Parameters: Users can customize parameters such as Tenkan, Kijun, and Senkou Span lengths, along with multipliers, to adjust the sensitivity of the Ichimoku Cloud.
Slope Filter Settings: Users can specify the number of bars to measure the slope and the lookback period for trend measurement. Additionally, there are options to filter Ichimoku signals based on slope thresholds.
Normalized Slope: The indicator calculates the normalized slope of the selected data series (in this case, Tenkan-sen) and plots it alongside the Ichimoku Cloud.
Signal Generation: Trading signals are generated based on crossovers and crossunders of the Tenkan-sen and Kijun-sen lines of the Ichimoku Cloud. These signals can be further filtered based on the normalized slope of the selected data series.
🔶 Usage:
Customization: Traders can customize the parameters of the Ichimoku Cloud and slope filter according to their trading strategy and risk tolerance.
Interpretation of Signals:
Crossover: A buy signal is generated when the Tenkan-sen line crosses above the Kijun-sen line. This signal can be further filtered based on the normalized slope.
Crossunder: A sell signal is generated when the Tenkan-sen line crosses below the Kijun-sen line. Similar to the buy signal, this can also be filtered based on the normalized slope.
Trend Confirmation: The normalized slope provides additional confirmation of the strength and direction of the trend. A positive slope indicates an upward trend, while a negative slope indicates a downward trend.
Example:
Disclaimer:
Not Financial Advice: This script is provided for educational purposes only and should not be considered financial advice. Traders should conduct their own research and/or consult with a qualified financial advisor before making any investment decisions based on this script.
Risk of Loss: Trading in financial markets involves risk of loss, and past performance is not indicative of future results. Users of this script should be aware of the risks involved in trading and should only trade with capital they can afford to lose.
No Guarantees: There is no guarantee of success or profitability when using this script. Market conditions can change rapidly, and trading results may vary.
Use at Own Risk: The author of this script (UAlgo) does not assume any responsibility for losses incurred as a result of using this script. Traders use this script at their own risk and discretion.
Terms of Use: This script is subject to the terms of the Mozilla Public License 2.0. Users are encouraged to review the license terms before using or distributing the script.
[ADOL_]Trend_Oscillators_MTF
ENG) Trend_Oscillator_MTF
introduction)
This is a trend analyzer implemented in the form of an oscillator.
An oscillator is a technical analysis tool that identifies the direction of market trends and determines the time period. Making it an oscillator means creating range. By setting the upper and lower limits like this, the unlimited expansion area that can appear on the chart is limited. As a limited area is created, we can identify oversold and overbought areas, which is good for checking momentum.
Through oscillatorization, you can find overbought, oversold, and current trend areas.
It adopts MTF and is a simple but functional indicator.
To use multiple time frames, use the timeframe.multiplier function.
A table was created using the table.new function, and various information windows were installed on the right side of the chart.
I hope this can be a destination for many travelers looking for good landmarks.
- 8 types of moving averages can be selected (in addition to independently developed moving averages), trend area display, signal display, up to 3 multi-time chart overlapping functions, information table display, volatility and whipsaw search, and alerts are possible.
- You can set various time zones in Timeframe. With three timeframes, you can check the conditions overlapping time at a glance.
principle)
Set up two moving averages with different speeds and make the relative difference.
Create the speed difference between the two moving averages using methods such as over = crossover(fast, slow) and under = crossunder(fast, slow).
The point at which the difference in relative speed decreases is where the possibility of inflection is high. Through the cross code, you can find out when the speed difference becomes 0.
Simply crossing the moving average is easy. To fine-tune the speed difference, it is necessary to re-establish the relationship between functions.
Painting the green and red areas is designed to be painted when the three time frames overlap.
Using the code of fill(fast, slow, color = fast>= slow? color.green: color.red, transp = 80, title = "fillcolor")
You can color and distinguish areas.
MA: You can select the MA_type. This is a necessary option because the profit/loss ratio for each item varies depending on the type of moving average.
Start: The starting value to set the oscillator range.
End: This is the last value to set the oscillator range.
Lenght: This is the number of candles used to calculate the calculation formula in the oscillator.
Timeframe: Set the time to overlap with up to 3 time frames.
repaint: You can choose whether to apply repaint. The default is OFF.
The coding for repaint settings for the indicator was written using the recommended method recommended by TradingView.
reference :
security(syminfo.tickerid, tf, src)
Trading method)
With the Multi-Time-Frame (MTF) function, the time zone set in the indicator is displayed the same in any chart time zone.
The repaint problem that occurred when using MTF was resolved by referring to TradingView's recommended code.
User can decide whether to repaint or not. The default is OFF.
- signal
Buy and Sell signals are displayed when there are 3 stacks. Even if there is no triple overlap, you can decide to buy or sell at the point where the short-term line and long-term line intersect.
Entry is determined through Buy and Sell signals, and exit is determined through BL (BuyLoss) and SL (SellLoss).
BL and SL can also be applied as entry.
You can judge overlap by the color of the lines. When two conditions overlap, it is orange, and when one condition overlaps, it is blue.
- Divergence
Divergence is a signal that arises from a discrepancy between the oscillator and the actual price.
Divergence can be identified because the range is set with conditions that have upper and lower limits.
- trend line
As shown in the picture, draw a downward trend line connecting the high points in the same area.
As shown in the picture, an upward trend line is drawn connecting the low points in the same area.
It can be used to view trend line breakout points that candles cannot display.
- Find a property for sale by amplitude
When the low point in the red area and the high point in the green area occur, the difference is regarded as one amplitude and the range is set.
Here, one amplitude becomes a pattern value that can go up or down, and this pattern value acts as support/resistance. It was developed in a unique way that is different from traditional methods and has a high standard of accuracy. This works best when using that indicator. Use 1, 2, 3, or 4 multiples of the amplitude range.
A multiple of 2 is a position with a high probability of a retracement.
- Whipsaw & volatility search section
Whipsaw refers to a trick that causes frequent trading in a convergence zone or confuses the trend in the opposite direction before it occurs. Whip saws are usually seen as having technical limitations that are difficult to overcome.
To overcome this problem, the indicator was created to define a section where whipsaw and volatility can appear. If a whipsaw & volatility indicator section occurs, a big move may occur later.
Alert)
Buy, Sell, BuyLoss, SellLoss, Whipsaw alert
Disclaimer)
Scripts are for informational and educational purposes only. Use of the script does not constitute professional and/or financial advice. You are solely responsible for evaluating the risks associated with your script output and use of the script.
KOR) 트렌드_오실레이터_MTF
소개)
이것은 오실레이터 형태로 구현된 트렌드 분석기 입니다.
오실레이터는 시장의 추세방향을 확인하고 기간을 결정하는 기술적 분석 도구입니다. 오실레이터로 만드는 것은 범위가 생기는 것을 의미합니다. 이렇게 상한과 하한을 정함으로써, 차트에서 나타날 수 있는 무제한적인 확장영역이 제한됩니다. 제한된 영역이 만들어짐에 따라 우리는 과매도와 과매수 구간을 식별할 수 있게 되며, 모멘텀을 확인하기 좋습니다.
오실레이터화를 통해, 과매수와 과매도, 현재의 트렌드 영역을 잘 찾을 수 있습니다.
MTF를 채택했으며, 단순하지만, 기능적으로 훌륭한 지표입니다.
멀티타임프레임을 사용하기 위해 timeframe.multiplier 함수를 사용합니다.
table.new 함수를 사용하여 table을 만들고, 차트 우측에 여러가지 정보창을 갖췄습니다.
좋은 지표를 찾는 많은 여행자들에게 이곳이 종착지가 될 수 있기를 바랍니다.
- 이평선 종류 8종 선택(독자적으로 개발한 이평선 추가), 추세영역표시, 시그널 표기, 최대 3개 멀티타임차트 중첩기능, 정보테이블 표시, 변동성과 휩쏘찾기, 얼러트가 가능합니다.
- Timeframe에서 다양한 시간대를 설정할 수 있습니다. 3개의 Timeframe을 통해 시간을 중첩한 조건을 한눈에 확인할 수 있습니다.
원리)
속도가 다른 두 개의 이평선을 설정하고 상대적인 차이를 만듭니다.
over = crossover(fast, slow) , under = crossunder(fast, slow) 와 같은 방법으로 두개의 이평선의 속도차이를 만듭니다.
상대적 속도의 차이가 줄어드는 시점은 변곡의 가능성이 높은 자리입니다. cross code를 통해 속도차가 0이 되는 시점을 알 수 있습니다.
단순히 이평선을 교차하는 것은 쉽습니다. 세밀하게 속도차이를 조정하는데 함수간의 관계를 다시 설정할 필요가 있습니다.
초록색과 빨간색의 영역을 칠하는 것은 3가지 타임프레임이 중첩될 때 칠하도록 만들어졌습니다.
fill(fast, slow, color = fast>= slow? color.green: color.red, transp = 80, title = "fillcolor") 의 코드를 사용하여
영역을 색칠하고 구분할 수 있습니다.
MA : MA_유형을 선택할 수 있습니다. 이평선의 종류에 따라 종목당 손익비가 달라지므로 꼭 필요한 옵션입니다.
Start : 오실레이터 범위를 설정할 시작값입니다.
End : 오실레이터 범위를 설정할 마지막값입니다.
Lenght : 오실레이터에서 계산식을 산출하기 위한 캔들의 개수입니다.
Timeframe : 최대 3개의 타임프레임으로 중첩할 시간을 설정합니다.
repaint : 리페인팅을 적용할지 선택할 수 있습니다. 기본값은 OFF 입니다.
해당 지표의 리페인트 설정에 관한 코딩은 트레이딩뷰에서 권장하는 추천 방법으로 작성되었습니다.
참고 :
security(syminfo.tickerid, tf, src)
매매방법)
Multi-Time-Frame(MTF) 기능으로 지표에서 설정한 시간대가 어느 차트 시간대에서나 동일하게 표시됩니다.
MTF 사용시 발생하는 리페인트 문제는 트레이딩뷰의 권장코드를 참고하여 해결했습니다.
사용자가 리페인트 여부를 결정할 수 있습니다. 기본값은 OFF 입니다.
- 시그널
시그널의 Buy와 Sell은 3중첩일 경우 표시됩니다. 3중첩이 아니라도 단기선과 장기선이 교차되는 시점에서 매매를 결정할 수 있습니다.
Buy와 Sell 시그널에서 진입을 결정하고 BL(BuyLoss)와 SL(SellLoss) 에서 exit를 결정합니다.
BL과 SL을 진입으로 응용할 수도 있습니다.
라인의 컬러로 중첩을 판단할 수 있습니다. 2개의 조건이 중첩되면 오렌지, 1개의 조건이 중첩되면 블루컬러입니다.
- 다이버전스
다이버전스는 오실레이터와 실제 가격의 불일치에서 발생하는 신호입니다.
상한과 하한이 있는 조건으로 범위를 설정하였기 때문에 다이버전스를 식별가능합니다.
- 추세선
그림과 같이 같은 영역의 고점을 이어 하락추세선을 긋습니다.
그림과 같이 같은 영역의 저점을 이어 상승추세선을 긋습니다.
캔들이 표시할 수 없는 추세선돌파 지점을 볼 수 있게 활용가능합니다.
- 진폭으로 매물대 찾기
빨간색 영역의 저점과 초록색 영역의 고점이 발생할 때, 그 차이를 하나의 진폭으로 보고 범위를 설정합니다.
여기서 하나의 진폭은 위나 아래로 갈 수 있는 패턴값이 되며, 이 패턴값은 지지/저항으로 작용합니다. 전통적인 방식에 없는 독창적인 방식으로 개발된 것으로 정확성 높은 기준입니다. 이것은 해당 지표를 사용할 때 가장 잘 맞습니다. 진폭 범위의 1배수,2배수,3배수,4배수 자리를 사용합니다.
2배수 자리는 다시 돌아오는 되돌림 확률이 높은 위치입니다.
- 휩쏘&변동성 찾기 구간
휩쏘는 수렴구간에서 잦은 매매를 유발하거나, 추세가 발생하기 전에 반대방향으로 혼란을 주는 속임수를 의미합니다. 휩쏘는 보통 극복하기 어려운 기술적 한계로 여겨집니다.
해당지표에서는 이를 극복하기 위해 휩쏘와 변동성이 나타날 수 있는 구간을 정의하도록 만들었습니다. 휩쏘&변동성 표시 구간이 발생하면 이후 큰 움직임이 발생할 수 있습니다.
얼러트)
Buy, Sell, BuyLoss, SellLoss, Whipsaw alert
면책조항)
스크립트는 정보 제공 및 교육 목적으로만 사용됩니다. 스크립트의 사용은 전문적 및/또는 재정적 조언으로 간주되지 않습니다. 스크립트 출력 및 스크립트 사용과 관련된 위험을 평가하는 책임은 전적으로 귀하에게 있습니다.
Broadview Algorithmic StudioWelcome! This is the writeup for the Broadview Algorithmic Studio.
There are many unique features in this script.
- Broadview Underpriced & Overpriced
- Broadview Blackout Bollinger Bands
- Trailing Take Profit Suite
- Algorithmic Weights
- VSA Score
- Pip Change Log
- Activation Panel
- Weight Scanner
There are 116 primary inputs that allow users to algorithmically output unique DCA signal-sets. There are 85 inputs that allow users to control individual lengths, levels, thresholds, and multiplicative weights of the script. You will not find any other script with this many inputs, properly strung together for you to produce unlimited strategies for any market. The entire premise for the Broadview Algorithmic Studio is for users to be able to have extensive-cutting-edge features that allow them to produce more strategies, having control over every element that outputs a signal set. The number of unique strategies you can output with this script is VAST, and each continues to follow a safe DCA methodology.
This script is ready for use with 3Commas, interactive brokers, and other means of automation. It provides detailed information on Base Orders and Safety Orders, giving the number, cumulative spending, position average, and remaining balance for each SO in the series. Using this script we will explore the depths of strategic volume scaling, and the algorithms we use to determine spending.
Let me first start by saying the number of safe DCA-friendly signal-sets this script can output is absolutely staggering.
Let's limit the scope just to the Broadview Underpriced & Overpriced and Broadview Dominance indicators.
Each band of the Dominance Suite can be controlled individually with unique lengths, levels, and weights. This means the Dominance Suite can establish Bearish or Bullish dominance, in any market condition, and give it a unique overloading weight. The Broadview Underpriced & Overpriced indicator finally gives us the ability to establish these "market conditions" first with cycles. Of all the cycles this indicator establishes, the two primary are Underpriced & Overpriced. We determine this using a composite Overbought & Oversold with an Exponential Moving Average. So the script can now know, what cycle it is in, who is dominant during that cycle, and exactly how much weight in volume scaling the order should have.
Brand new is the ability for indicators of this level to be able to talk together in a single script. The Broadview Underpriced & Overpriced indicator and the Broadview Dominance indicator can inform one another across multiple vectors, create a unique market snapshot, and give that snapshot a unique weight every bar. The unique weight is compiled in the volume scaling math, thus giving us an automated-strategic-safe and quite efficient volume scaling for every order. In our coming updates we will explore this synergy to its very deepest layers. These indicators can be laced together in many ways, called vectors.
Only in the Algorithmic Studio do we explore these depths and yield those findings, features, and inputs to the user.
Let me take a quick break to explain another area-of-opportunity for our research and development.
The VSA Score is something we've tried before, but until the creation of the Broadview Blackout Bollinger Bands Auto Indicator it was not possible. The concept we want to explore is "Positional Honing". Over time we want users and the script itself to be able to understand the difference between a script-config that produces a high number of Hits, from a configuration that produces a high number of "Misses". The Volume Scaling Accuracy Score uses the BBB Auto Indicator as a heavily reliable, non-repainting, method of determining what the very-best signals for increased volume-scaling are.
Increased volume scaling is denoted by the near-white highlighter line running vertically. This line will either fall inside the BBB Auto Indicator bands (which are hidden), or, they will fall below and outside the BBB Auto bands. If increased spending happens inside the bands it's a "Miss". If increased spending happens below and outside the bands, it's a Hit. Oftentimes misses are actually pretty good spots for extra spending, which helps lower your position average, but Hits are always better. The Hits that the BBB Auto Indicator provides are extremely good.
Let's talk about the Trailing Take Profit Suite. This suite allows us to set a trailing take profit which is a feature that lets one maximize their profits. If the trailing take profit is engaged, then when the regular take profit is hit, it will trigger, denoted in red vertical lines, and the trailing take profit will look for a specified rate of change before it actually takes profit. This usually helps traders in those times when their regular take profit was set too low, allowing them to maximize their profits with a Trailing Take Profit.
For the moment, let's think about our scores. In the dashboard you'll notice a score beginning the Pip Change Log, the VSA Score, and the Activation Panel.
These scores use a new kind of logistic correlation formula where 4 digits are given to activation, rather than 1. This is to allow room for a future concept in AI we call "Deadzones" or you can think of it as impedance. This is not a bias in logistic regression. It's an entirely different concept. A neuron, which a perceptron attempts to mimic, has a bias.. but it also has a sort of electrical resistance. This is because a neuron is individually-alive entity. So a perceptron, as it were, would need to have both a bias and a natural resistance, or deadzone.
It is a lot of fun to watch the scores and how they react during playback. They tend to smooth trends but are also quite quick to correct to accuracy. In the future we will add the deadzones and biases to the scores. This should help both users and the script produce better signal sets. The Pip Change Log is an indicator that measures Rate of Change in Pips. This is one that I am particularly excited to study, as I am a huge fan of ROC. The Activation Panel shows these scores for 4 primary indicators: On Balance Volume, Relative Strength Index, Average Directional Index, and Average True Range.
Having the Pip Change Log, VSA Score, and Activation Panel up on the dashboard with their logistic correlation scores allows traders to study markets and setups quite intimately. The weight scanner at the bottom allows users to track the cumulative applied multiplicative weights during playback. The massive number of inputs, connected vectors of indicators, input-weights, lengths, levels, and thresholds sets up all the algorithmic infrastructure for powerusers to explore every idea and strategy output they could imagine. Also with the connected vector infrastructure we can deepen our indicators in a way where, "How they talk to each other.", comes first in every development conversation.
The Algorithmic Studio is for the Power-user.
These are not basic equations coming together to determine spending. This is a massive multi-layered-perceptron with everything from Trailing-Take-Profits to strategic-automatic algorithmic downscaling. The Broadview Algorithmic Studio gives a home to the poweruser who wants access to everything in a trading and investing AI, right up until the backpropagation. The Broadview Algorithmic Studio, gives users the ability to sit in the chair of the would-be AI.
Thank you.
Selected Dates Filter by @zeusbottradingWe are presenting you feature for strategies in Pine Script.
This function/pine script is about NOT opening trades on selected days. Real usage is for bank holidays or volatile days (PPI, CPI, Interest Rates etc.) in United States and United Kingdom from 2020 to 2030 (10 years of dates of bank holidays in mentioned countries above). Strategy is simple - SMA crossover of two lengts 14 and 28 with close source.
In pine script you can see we picked US and GB bank holidays. If you add this into your strategy, your bot will not open trades on those days. You must make it a rule or a condition. We use it as a rule in opening long/short trades.
You can also add some of your prefered dates, here is just example of our idea. If you want to add your preffered days you can find them on any site like forexfactory, myfxbook and so on. But don’t forget to add function “time_tradingday ! = YourChoosedDate” as it is writen lower in the pine script.
Sometimes the date is substituted for a different day, because the day of the holiday is on Saturday or Sunday.
Made with ❤️ for this community.
If you have any questions or suggestions, let us know.
The script is for informational and educational purposes only. Use of the script does not constitutes professional and/or financial advice. You alone the sole responsibility of evaluating the script output and risks associated with the use of the script. In exchange for using the script, you agree not to hold zeusbottrading TradingView user liable for any possible claim for damages arising from any decision you make based on use of the script.
[ChasinAlts]Top-Wicked Good S/R LinesHello Tradeurs, as per usual, I hope everyone is having a FAN-FRIGGIN-TASTIC day. With the soon incoming bull market approaching fast(Nov 7, 2022), there are a few ideas that I've really been trying to push out to help nail a few coins as they are near their bottom peak of this closing Bear Market. This one may seem very similar to the last one I posted but I think this one takes the cake...esp when you see the next script from my 'Market Overview' series that I will be publishing shortly after this one as it is utilizing this new script for a market scanner that will be SUPER legit and profitable. Though it is alway nice to be noticed, I'm glad that I'm relatively unpopular so the few people that are now following me can have some time to make some money with some of these scripts I'm trying to pump out for the benefit of the community. I will rarely give my full analysis of how I take in and utilize these scripts but I can tell you, QUITE A FEW of them are money in the bank. Esp these last few I've done/am doing and even more-so the ones that are soon to come (I'm speaking of about the next 3-4 that I will be attempting to pump out in this next VERY IMPORTANT week.). One more thing I'll add before going to the script is a little alpha(Im pretty certain this is the way it is going but NOTHING is EVERY 100% in life). What I believe should be realized is the bottoming out of MANY of the crypto coins at the VERY bottom of a LONG TERM Cup and Handle (so it seems but shat can still change in the blink of an eye). Thus there are quite a few coins that I believe have already bottomed and wont be returning to said bottom for a few years or so but there are also quite a few still at the brink of the bottomest part before the real market breakout occurs. My goal with these scripts coming out this week to help you all find those coins that have yet to hit their very bottom (thus the ATH/ATL script recently published). Going back in history looking for the lowest points of long term Cup & Handles I will point out 2 key things. Near the center/bottomest part of these historical CnH you will see either Double Bottoms OR a Huge dump and then its V-shaped recovery. After these print the point of no return has occurred where only a few coins will be going lower than these Double Bottoms/V-Shaped recoveries. So the time is at hand. Now that many coins are seemingly pumping after this long consolidation, I believe we need to keep a keen eye out for THE FINAL RUG PULL (as soon as enough degenerates are leveraging Long their entire savings.). What Im saying is be ready for this final rug pull to finally be seeing these Double Bottoms/V-Shaped recoveries VERY soon. DO NOT waste all your capital yet and MAKE SURE to use stop losses or else rather than stop losses you will be burdened with MUCH WORSE losses. Im currently not even in the market bc I am waiting on said rug pull. Ok for the Script now.
This script is similar to the last one but with the previous one, one general set of settings can produce VASTLY different results (might have 2 S/R lines on one coin and 80 on another). I wanted to fix that with this script, turn it into a "Market Overview" Scanner and create alerts for the MO Scanner to be able to get alerted any time a coin is passing its largest wick S/R levels bc DULY NOTE...it is VERY rare that a coin will blow past it if it hasn't approached it recently. That means that a small retrace of 3-5%(or more) is EASY to acquire (with leverage that can really add up with how many coins are in the Kucoin Margin Coin list that I have in my scanners). Now, once price does shoot through a level you best be sure to be looking down the line for a retest of the S/R level it blew past before as they are MANY times the retest level and price will be coming back to it before continuing
in the direction it was going. Depending on the TF your using this could be a few hours to a few days to a few weeks...you get it. With this script you can choose to draw S/R lines 2 ways: 1) by having it plot S/R lines on the end of the largest 2(3,4,5..however many you choose) wicks that the chart has access to. For the scanner ill just be putting the largest 2-3 wicks and set alerts when coming up to them/crossing them & 2) having it draw S/R lines on the ends of the largest X% of wicks. it will be erasing the lines and drawing new ones on each new candle occurrence so the same general settings will no longer be producing VASTLY diff amounts of S/R lines and will be way more consistent amongst the coins for better utilization with the scanner (when I publish it). There is also a Wick Max Cutoff % so for those coins that had it's first few hours printing 100% sized wicks...you can choose to ignore them so they are not taking up one of your top spots for the S/R lines. There is similarly a Wick % min Size that can be selected so if you’re using the top % setting, it will help decrease those coins that can be still plotting 30 lines even though the top 3% of the largest wicks are set in the settings. Hope Im being clear but it's easy enough. I believe in you and your capabilities of comprehending it all and getting it all figured out. So this script is for a visualization for the scanner that I will be uploading soon-after. It's always nice to get a few comments if my ideas/scripts have been helpful to you and please don't hold back if you have something to tell me that I screwed up on (I am still rather new to this coding thing but I like to think I at least have some fresh ideas that aren’t out there in the public library). Talk to you soon and may the force be with your trades. Peace and love people...peace and love. -ChasinAlts out.
Candlestick Pattern Criteria and Analysis Indicator█ OVERVIEW
Define, then locate the presence of a candle that fits a specific criteria. Run a basic calculation on what happens after such a candle occurs.
Here, I’m not giving you an edge, but I’m giving you a clear way to find one.
IMPORTANT NOTE: PLEASE READ:
THE INDICATOR WILL ALWAYS INITIALLY LOAD WITH A RUNTIME ERROR. WHEN INITIALLY LOADED THERE NO CRITERIA SELECTED.
If you do not select a criteria or run a search for a criteria that doesn’t exist, you will get a runtime error. If you want to force the chart to load anyway, enable the debug panel at the bottom of the settings menu.
Who this is for:
- People who want to engage in TradingView for tedious and challenging data analysis related to candlestick measurement and occurrence rate and signal bar relationships with subsequent bars. People who don’t know but want to figure out what a strong bullish bar or a strong bearish bar is.
Who this is not for:
- People who want to be told by an indicator what is good or bad or buy or sell. Also, not for people that don’t have any clear idea on what they think is a strong bullish bar or a strong bearish bar and aren’t willing to put in the work.
Recommendation: Use on the candle resolution that accurately reflects your typical holding period. If you typically hold a trade for 3 weeks, use 3W candles. If you hold a trade for 3 minutes, use 3m candles.
Tldr; Read the tool tips and everything above this line. Let me know any issues that arise or questions you have.
█ CONCEPTS
Many trading styles indicate that a certain candle construct implies a bearish or bullish future for price. That said, it is also common to add to that idea that the context matters. Of course, this is how you end up with all manner of candlestick patterns accounting for thousands of pages of literature. No matter the context though, we can distill a discretionary trader's decision to take a trade based on one very basic premise: “A trader decides to take a trade on the basis of the rightmost candle's construction and what he/she believes that candle construct implies about the future price.” This indicator vets that trader’s theory in the most basic way possible. It finds the instances of any candle construction and takes a look at what happens on the next bar. This current bar is our “Signal Bar.”
█ GUIDE
I said that we vet the theory in the most basic way possible. But, in truth, this indicator is very complex as a result of there being thousands of ways to define a ‘strong’ candle. And you get to define things on a very granular level with this indicator.
Features:
1. Candle Highlighting
When the user’s criteria is met, the candle is highlighted on the chart.
The following candle is highlighted based on whether it breaks out, breaks down, or is an inside bar.
2. User-Defined Criteria
Criteria that you define include:
Candle Type: Bull bars, Bear bars, or both
Candle Attributes
Average Size based on Standard Deviation or Average of all potential bars in price history
Search within a specific price range
Search within a specific time range
Clarify time range using defined sessions and with or without weekends
3. Strike Lines on Candle
Often you want to know how price reacts when it gets back to a certain candle. Also it might be true that candle types cluster in a price region. This can be identified visually by adding lines that extend right on candles that fit the criteria.
4. User-Defined Context
Labeled “Alternative Criteria,” this facet of the script allows the user to take the context provided from another indicator and import it into the indicator to use as a overriding criteria. To account for the fact that the external indicator must be imported as a float value, true (criteria of external indicator is met) must be imported as 1 and false (criteria of external indicator is not met) as 0. Basically a binary Boolean. This can be used to create context, such as in the case of a traditional fractal, or can be used to pair with other signals.
If you know how to code in Pinescript, you can save a copy and simply add your own code to the section indicated in the code and set your bull and bear variables accordingly and the code should compile just fine with no further editing needed.
Included with the script to maximize out-of-the-box functionality, there is preloaded as alternative criteria a code snippet. The criteria is met on the bull side when the current candle close breaks out above the prior candle high. The bear criteria is met when the close breaks below the prior candle. When Alternate Criteria is run by itself, this is the only criteria set and bars are highlighted when it is true. You can qualify these candles by adding additional attributes that you think would fit well.
Using Alternative Criteria, you are essentially setting a filter for the rest of the criteria.
5. Extensive Read Out in the Data Window (right side bar pop out window).
As you can see in the thumbnail, there is pasted a copy of the Data Window Dialogue. I am doubtful I can get the thumbnail to load up perfectly aligned. Its hard to get all these data points in here. It may be better suited for a table at this point. Let me know what you think.
The primary, but not exclusive, purpose of what is in the Data Window is to talk about how often your criteria happens and what happens on the next bar. There are a lot of pieces to this.
Red = Values pertaining to the size of the current bar only
Blue = Values pertaining or related to the total number of signals
Green = Values pertaining to the signal bars themselves, including their measurements
Purple = Values pertaining to bullish bars that happen after the signal bar
Fuchsia = Values pertaining to bearish bars that happen after the signal bar
Lime = Last four rows which are your percentage occurrence vs total signals percentages
The best way I can explain how to understand parts you don’t understand otherwise in the data window is search the title of the row in the code using ‘ctrl+f’ and look at it and see if it makes more sense.
█ [b}Available Candle Attributes
Candle attributes can be used in any combination. They include:
[*}Bodies
[*}High/Low Range
[*}Upper Wick
[*}Lower Wick
[*}Average Size
[*}Alternative Criteria
Criteria will evaluate each attribute independently. If none is set for a particular attribute it is bypassed.
Criteria Quantity can be in Ticks, Points, or Percentage. For percentage keep in mind if using anything involving the candle range will not work well with percentage.
Criteria Operators are “Greater Than,” “Less Than,” and “Threshold.” Threshold means within a range of two numbers.
█ Problems with this methodology and opportunities for future development:
#1 This kind of work is hard.
If you know what you’re doing you might be able to find success changing out the inputs for loops and logging results in arrays or matrices, but to manually go through and test various criteria is a lot of work. However, it is rewarding. At the time of publication in early Oct 2022, you will quickly find that you get MUCH more follow through on bear bars than bull bars. That should be obvious because we’re in the middle of a bear market, but you can still work with the parameters and contextual inputs to determine what maximizes your probability. I’ve found configurations that yield 70% probability across the full series of bars. That’s an edge. That means that 70% of the time, when this criteria is met, the next bar puts you in profit.
#2 The script is VERY heavy.
Takes an eternity to load. But, give it a break, it’s doing a heck of a lot! There is 10 unique arrays in here and a loop that is a bit heavy but gives us the debug window.
#3 If you don’t have a clear idea its hard to know where to start.
There are a lot of levers to pull on in this script. Knowing which ones are useful and meaningful is very challenging. Combine that with long load times… its not great.
#4 Your brain is the only thing that can optimize your results because the criteria come from your mind.
Machine learning would be much more useful here, but for now, you are the machine. Learn.
#5 You can’t save your settings.
So, when you find a good combo, you’ll have to write it down elsewhere for future reference. It would be nice if we could save templates on custom indicators like we can on some of the built in drawing tools, but I’ve had no success in that. So, I recommend screenshotting your settings and saving them in Notion.so or some other solid record keeping database. Then you can go back and retrieve those settings.
#6 no way to export these results into conditions that can be copy/pasted into another script.
Copy/Paste of labels or tables would be the best feature ever at this point. Because you could take the criteria and put it in a label, copy it and drop it into another strategy script or something. But… men can dream.
█ Opportunities to PineCoders Learn:
1. In this script I’m importing libraries, showing some of my libraries functionality. Hopefully that gives you some ideas on how to use them too.
The price displacement library (which I love!)
Creative and conventional ways of using debug()
how to display arrays and matrices on charts
I didn’t call in the library that holds the backtesting function. But, also demonstrating, you can always pull the library up and just copy/paste the function out of there and into your script. That’s fine to do a lot of the time.
2. I am using REALLY complicated logic in this script (at least for me). I included extensive descriptions of this ? : logic in the text of the script. I also did my best to bracket () my logic groups to demonstrate how they fit together, both for you and my future self.
3. The breakout, built-in, “alternative criteria” is actually a small bit of genius built in there if you want to take the time to understand that block of code and think about some of the larger implications of the method deployed.
As always, a big thank you to TradingView and the Pinescript community, the Pinescript pros who have mentored me, and all of you who I am privileged to help in their Pinescripting journey.
"Those who stay will become champions" - Bo Schembechler
BCT Buy And Hold w/ Advanced StatisticsThis is a script designed to simulate a buy and hold strategy in the chart that its applied to.
Tradingview backtester is really limited in the statistics it gives you based on equity and information of open trades. For that reason many of the buy and hold scripts suffer from the same problem, a lack of useful statistics about your buy and hold strategy.
This script allows you to filter a specific buy and hold period (or use the whole data available in the tradingivew chart) and get useful statistics based on equity on a bar by bar basis.
Date Range Filtering
This allows you to chose a specific period to test the buy and hold strategy and to visualize the statistics.
We include 3 main tables which offer useful information so you can compare your strategy vs buy and hold strategy.
This 3 tables are:
Draw Downs Table
This table shows the Current P/L, Current Draw Down, Average and Maximum Draw Downs based on the equity of the buy and hold strategy calculated by candle. This can show you how much average and maximum loss or pain you would have to go through in order to stick to the buy and hold strategy.
Custom Statistics Table
This table shows useful advanced statistics to compare the buy and hold strategy to other strategies.
CAGR: Compounded annual growth rate is the industry standard in terms of showing annualized returns for any strategy or investment.
Annualized Return ($)
Trade Duration (Days): Self explanatory, displays how long the buy and hold trade was open or is open counted in days.
Max Stagnation Period (Days): Measures the Maximum time taken between new equity highs.
Average Draw Down : Average value of all draw downs from equity highs over the period (sampled 1 time per candle).
Maximum Draw Down : Largest draw down from equity highs in the whole period.
Return / Avg DrawDown: Advanced Proprietary statistic in which the annualized (non compounding) return is divided by the Average Draw Down (displayed in the Draw Downs Table)
Return / Maximum DrawDown: Advanced statistic in which the annualized (non compounding) return is divided by the Maximum Draw Down (displayed in the Draw Downs Table)
CAGR / Avg DrawDown: Advanced Proprietary statistic in which the CAGR (compounding) is divided by the Average Draw Down (displayed in the Draw Downs Table)
CAGR / Maximum DrawDown: Advanced Proprietary statistic in which the CAGR (compounding) is divided by the Maximum Draw Down (displayed in the Draw Downs Table)
Note: All the advanced statistics show, in slightly different ways, how much a strategy compensates you in relation to the risk taken. In other words you can see this as a way to quantify risk adjusted returns between multiple strategies. We prefer using the CAGR based advanced Statistics as they give a more universal value to compare across multiple strategies and asset classes.
In Sample / Out Of Sample Custom Stats (IS/OOS) Table
This table shows similar statistics as the Custom Statistics Table but is able to break down the backtest period into segments, this is useful when testing strategies as it can be used to test optimization quality. In this Buy and Hold strategy this can be used to visualize the stats of 2 periods at the same time and compare them without need to change settings or use another instance of the script.
All the Stats are the same as in the Custom Statistics Table with the difference of some being removed and the table being constructed in a way that facilitates the comparison of stats between In Sample, Out Of Sample and Full periods
DMI + HMA - No Risk ManagementDMI (Directional Movement Index) and HMA (Hull Moving Average)
The DMI and HMA make a great combination, The DMI will gauge the market direction, while the HMA will add confirmation to the trend strength.
What is the DMI?
The DMI is an indicator that was developed by J. Welles Wilder in 1978. The Indicator was designed to identify in which direction the price is moving. This is done by comparing previous highs and lows and drawing 2 lines.
1. A Positive movement line
2. A Negative movement line
A third line can be added, which would be known as the ADX line or Average Directional Index. This can also be used to gauge the strength in which direction the market is moving.
When the Positive movement line (DI+) is above the Negative movement line (DI-) there is more upward pressure. Ofcourse visa versa, when the DI- is above the DI+ that would indicate more downwards pressure.
Want to know more about HMA? Check out one of our other published scripts
What is this strategy doing?
We are first waiting for the DMI to cross in our favoured direction, after that, we wait for the HMA to signal the entry. Without both conditions being true, no trade will be made.
Long Entries
1. DI+ crosses above DI-
2. HMA line 1 is above HMA line 2
Short Entries
1. DI- Crosses above DI+
2. HMA line 1 is below HMA lilne 2
Its as simple as that.
Conclusion
While this strategy does have its downsides, that can be reduced by adding some risk manegment into the script. In general the trade profitability is above average, And the max drawdown is at a minimum.
The settings have been optimised to suite BTCUSDT PERP markets. Though with small adjustments it can be used on many assets!
Strat AssistantStrat Assistant
This script will help you follow the strat. While other collections of scripts exist to do similar functionality, the idea of this (work in progress) is to be a one stop shop for all things strat that will evolve over time. Fairly new to the strat and pine script. The script is for informational purposes only. Please do you due diligence.
Features:
=Candle numbering: will number candles underneath based on the prior candle. 1 for an inside bar 2 for a directional bar (up or down) and 3 for an outside bar.
=Candle coloring: will highlight candles. Yellow for an inside candle, magenta for an outside candle, red for a 2 down candle, green for a 2 up candle. It will not modify the outside border of the candle so you can still see green if the open was lower than the close or red if the close was below open.
=Candle shape: will place an arrow up if the 2 candle is a directional UP and arrows down if the 2 candle is a directional DOWN. It will display red if it's bearish and green if it's bullish.
=Strat combos: will provide a text description of all currently applicable strat combinations if they are active at the top right of the chart. It will display red if it's bearish and green if it's bullish.
=Actionable signals: will provide text description of actionable signals if they are active on the bottom right of the chart. Inside bar if the bar is inside the prior bar, the color of this signal will be blue (shows better on white background). Hammer will be 75% of the candle is at the bottom and the open and close are above the 75% of the wick. Hammers will display green for bullish. Shooters are just the opposite of hammers, 75% of the wick is at the top and the open and close are below 75% of the wick. Shooters will display at red for bearish.
=Time Frame Continuity: will provide time frame continuity across 15m, 30m, Hour, Day, Week, Quarter, Year with green arrows up if the close is above the open for the given time frame, or red arrows down if the close is below the open for the given time frame. This will also look to determine if the time frame is applicable based on what time frame the user selects as well as ensures history exists for the given time frame.
Backlog / Work in progress:
=Opacity for time frame continuity
=Line indicators (or maybe just a label) for highs and lows of previous periods (hour, day, week, quarter)
=Alert conditions
=User input for various indicators